
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>测试工具 &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="进阶测试主题" href="advanced.html" />
    <link rel="prev" title="编写并运行测试" href="overview.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);(function($) {
    $(document).ready(function() {
        $(".c-tab-unix").on("click", function() {
            $("section.c-content-unix").show();
            $("section.c-content-win").hide();
            $(".c-tab-unix").prop("checked", true);
        });
        $(".c-tab-win").on("click", function() {
            $("section.c-content-win").show();
            $("section.c-content-unix").hide();
            $(".c-tab-win").prop("checked", true);
        });
    });
})(jQuery);</script>
<link rel="stylesheet" href="../../_static/console-tabs.css" type="text/css" />
  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="overview.html" title="编写并运行测试">previous</a>
     |
    <a href="../index.html" title="使用 Django" accesskey="U">up</a>
   |
    <a href="advanced.html" title="进阶测试主题">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-testing-tools">
            
  <div class="section" id="s-testing-tools">
<span id="testing-tools"></span><h1>测试工具<a class="headerlink" href="#testing-tools" title="永久链接至标题">¶</a></h1>
<p>Django 提供了一小组在编写测试时会派上用场的工具。</p>
<div class="section" id="s-the-test-client">
<span id="s-test-client"></span><span id="the-test-client"></span><span id="test-client"></span><h2>测试客户端<a class="headerlink" href="#the-test-client" title="永久链接至标题">¶</a></h2>
<p>测试客户端是一个 Python 类，它充当一个虚拟的 Web 浏览器，允许你测试视图并以编程方式与 Django 驱动的应用程序交互。</p>
<p>你可以使用测试客户端执行以下操作：</p>
<ul class="simple">
<li>模拟 URL 上的 GET 和 POST 请求并观察响应——从低级 HTTP（结果头和状态码）到页面内容，应有尽有。</li>
<li>查看重定向链（如果有的话），并检查每个步骤的 URL 和状态码。</li>
<li>测试给定的请求是否由给定的包含某些值以及模板上下文的 Django 模板渲染。</li>
</ul>
<p>请注意，测试客户端并不是要取代 <a class="reference external" href="https://www.selenium.dev/">Selenium</a> 或其他“浏览器内”框架。Django 的测试客户端有不同的侧重点。简而言之：</p>
<ul class="simple">
<li>使用 Django 的测试客户端来确定要渲染的模板正确，并且模板已传递了正确的上下文数据。</li>
<li>使用如 <a class="reference external" href="https://www.selenium.dev/">Selenium</a> 之类的浏览器内框架来测试 <em>渲染后的</em> HTML 和 Web 页面 <em>行为</em>，即 JavaScript 功能。Django 也为这些框架提供了特殊的支持，详情参见 <a class="reference internal" href="#django.test.LiveServerTestCase" title="django.test.LiveServerTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">LiveServerTestCase</span></code></a>。</li>
</ul>
<p>一个全面的测试套件应该使用这两种测试类型的组合。</p>
<div class="section" id="s-overview-and-a-quick-example">
<span id="overview-and-a-quick-example"></span><h3>概述和一个简单的例子<a class="headerlink" href="#overview-and-a-quick-example" title="永久链接至标题">¶</a></h3>
<p>要使用测试客户端，请实例化 <code class="docutils literal notranslate"><span class="pre">django.test.Client</span></code> 并检索 Web 页面：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">Client</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">response</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s1">&#39;/login/&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;username&#39;</span><span class="p">:</span> <span class="s1">&#39;john&#39;</span><span class="p">,</span> <span class="s1">&#39;password&#39;</span><span class="p">:</span> <span class="s1">&#39;smith&#39;</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span>
<span class="go">200</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">response</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/customer/details/&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">response</span><span class="o">.</span><span class="n">content</span>
<span class="go">b&#39;&lt;!DOCTYPE html...&#39;</span>
</pre></div>
</div>
<p>如本例所示，你可以从 Python 交互式解释器的会话中实例化 <code class="docutils literal notranslate"><span class="pre">Client</span></code>。</p>
<p>请注意测试客户端如何工作的一些重要事项：</p>
<ul>
<li><p class="first">测试客户端 <em>不</em> 需要运行 Web 服务器。事实上，在没有 Web 服务器运行的情况下，它也能运行得很好！这是因为它避免了 HTTP 的开销并直接处理 Django 框架。这有助于使单元测试快速运行。</p>
</li>
<li><p class="first">检索页面时，请记住指定 URL 的 <em>路径</em>，而不是整个域。例如，这是正确的：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/login/&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>这是错误的：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;https://www.example.com/login/&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>测试客户端无法检索不是由你的 Django 项目驱动的 Web 页面。如果你需要检索其他网页，请使用 Python 标准库模块，如 <a class="reference external" href="https://docs.python.org/3/library/urllib.html#module-urllib" title="(在 Python v3.10)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a>。</p>
</li>
<li><p class="first">为了解析 URL，测试客户端使用你的 <a class="reference internal" href="../../ref/settings.html#std:setting-ROOT_URLCONF"><code class="xref std std-setting docutils literal notranslate"><span class="pre">ROOT_URLCONF</span></code></a> 配置指向的任何 URLconf。</p>
</li>
<li><p class="first">虽然上面的例子可以在 Python 交互式解释器中工作，但是测试客户端的一些功能，尤其是与模板相关的功能，只有在 <em>测试运行时</em> 才可以使用。</p>
<p>原因是 Django 的测试运行器为了确定哪个模板被给定的视图加载，执行了一点黑魔法。这个黑魔法（本质上是内存中 Django 模板系统的补丁）只发生在测试运行期间。</p>
</li>
<li><p class="first">默认情况下，测试客户端将禁用站点执行的任何 CSRF 检查。</p>
<p>如果出于某种原因，你 <em>想</em> 让测试客户端执行 CSRF 检查，则可以创建强制执行 CSRF 检查的测试客户端实例。为此，请在构建客户端时传递 <code class="docutils literal notranslate"><span class="pre">enforce_csrf_checks</span></code> 参数：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">Client</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">csrf_client</span> <span class="o">=</span> <span class="n">Client</span><span class="p">(</span><span class="n">enforce_csrf_checks</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
</li>
</ul>
</div>
<div class="section" id="s-making-requests">
<span id="making-requests"></span><h3>发出请求<a class="headerlink" href="#making-requests" title="永久链接至标题">¶</a></h3>
<p>使用 <code class="docutils literal notranslate"><span class="pre">django.test.Client</span></code> 类发出请求。</p>
<dl class="class">
<dt id="django.test.Client">
<em class="property">class </em><code class="descname">Client</code>(<em>enforce_csrf_checks=False</em>, <em>json_encoder=DjangoJSONEncoder</em>, <em>**defaults</em>)<a class="headerlink" href="#django.test.Client" title="永久链接至目标">¶</a></dt>
<dd><p>它在构造时不需要任何参数。然而，你可以使用关键字参数来指定一些默认头信息。例如，这将在每个请求中发送一个 <code class="docutils literal notranslate"><span class="pre">User-Agent</span></code> HTTP 头：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">(</span><span class="n">HTTP_USER_AGENT</span><span class="o">=</span><span class="s1">&#39;Mozilla/5.0&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>传递给 <a class="reference internal" href="#django.test.Client.get" title="django.test.Client.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a>、<a class="reference internal" href="#django.test.Client.post" title="django.test.Client.post"><code class="xref py py-meth docutils literal notranslate"><span class="pre">post()</span></code></a> 等方法的 <code class="docutils literal notranslate"><span class="pre">extra</span></code> 关键字参数的值，优先于传递给类构造函数的默认值。</p>
<p><code class="docutils literal notranslate"><span class="pre">enforce_csrf_checks</span></code> 参数可用于测试 CSRF 保护（见上文）。</p>
<p><code class="docutils literal notranslate"><span class="pre">json_encoder</span></code> 参数允许为 <a class="reference internal" href="#django.test.Client.post" title="django.test.Client.post"><code class="xref py py-meth docutils literal notranslate"><span class="pre">post()</span></code></a> 中描述的 JSON 序列化设置一个自定义 JSON 编码器。</p>
<p><code class="docutils literal notranslate"><span class="pre">raise_request_exception</span></code> 参数允许控制是否在请求过程中引出的异常也应该在测试中引出。默认值为 <code class="docutils literal notranslate"><span class="pre">True</span></code>。</p>
<p>一旦有了 <code class="docutils literal notranslate"><span class="pre">Client</span></code> 实例，就可以调用以下任何一种方法：</p>
<dl class="method">
<dt id="django.test.Client.get">
<code class="descname">get</code>(<em>path</em>, <em>data=None</em>, <em>follow=False</em>, <em>secure=False</em>, <em>**extra</em>)<a class="headerlink" href="#django.test.Client.get" title="永久链接至目标">¶</a></dt>
<dd><p>对提供的 <code class="docutils literal notranslate"><span class="pre">path</span></code> 上发出 GET 请求，并返回一个 <code class="docutils literal notranslate"><span class="pre">Response</span></code> 对象，如下所述。</p>
<p><code class="docutils literal notranslate"><span class="pre">data</span></code> 字典中的键值对用于创建 GET 数据有效载荷。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/customers/details/&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;fred&#39;</span><span class="p">,</span> <span class="s1">&#39;age&#39;</span><span class="p">:</span> <span class="mi">7</span><span class="p">})</span>
</pre></div>
</div>
<p>......将产生等效的 GET 请求：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>/customers/details/?name=fred&amp;age=7
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">extra</span></code> 关键词参数可以用来指定请求中要发送的头信息。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/customers/details/&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;fred&#39;</span><span class="p">,</span> <span class="s1">&#39;age&#39;</span><span class="p">:</span> <span class="mi">7</span><span class="p">},</span>
<span class="gp">... </span>      <span class="n">HTTP_ACCEPT</span><span class="o">=</span><span class="s1">&#39;application/json&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>......会将 HTTP 头 <code class="docutils literal notranslate"><span class="pre">HTTP_ACCEPT</span></code> 发送到 detail 视图，这是测试使用 <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest.accepts" title="django.http.HttpRequest.accepts"><code class="xref py py-meth docutils literal notranslate"><span class="pre">django.http.HttpRequest.accepts()</span></code></a> 方法的代码路径的好方法。</p>
<div class="admonition-cgi-specification admonition">
<p class="first admonition-title">CGI 规范</p>
<p class="last">通过 <code class="docutils literal notranslate"><span class="pre">**extra</span></code> 发送的头信息应遵循 <a class="reference external" href="https://www.w3.org/CGI/">CGI</a> 规范。例如，在浏览器向服务器发送的 HTTP 请求中，模拟不同的“Host”头，应以 <code class="docutils literal notranslate"><span class="pre">HTTP_HOST</span></code> 的形式发送。</p>
</div>
<p>如果你已经有了 URL 编码形式的 GET 参数，你可以使用该编码代替使用数据参数。例如，之前的 GET 请求也可以改成：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/customers/details/?name=fred&amp;age=7&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>如果你提供的 URL 同时包含编码的 GET 数据和数据参数，数据参数将优先。</p>
<p>如果将 <code class="docutils literal notranslate"><span class="pre">follow</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，客户端将遵循所有重定向，并且将在响应对象中设置 <code class="docutils literal notranslate"><span class="pre">redirect_chain</span></code> 属性，该属性是包含中间 URL 和状态码的元组。</p>
<p>如果你有一个 URL <code class="docutils literal notranslate"><span class="pre">/redirect_me/</span></code>，重定向到 <code class="docutils literal notranslate"><span class="pre">/next/</span></code>，再重定向到 <code class="docutils literal notranslate"><span class="pre">/final/</span></code>，这是你会看到的：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">response</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/redirect_me/&#39;</span><span class="p">,</span> <span class="n">follow</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">response</span><span class="o">.</span><span class="n">redirect_chain</span>
<span class="go">[(&#39;http://testserver/next/&#39;, 302), (&#39;http://testserver/final/&#39;, 302)]</span>
</pre></div>
</div>
<p>如果你把 <code class="docutils literal notranslate"><span class="pre">secure</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，则客户端将模拟 HTTPS 请求。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.Client.post">
<code class="descname">post</code>(<em>path</em>, <em>data=None</em>, <em>content_type=MULTIPART_CONTENT</em>, <em>follow=False</em>, <em>secure=False</em>, <em>**extra</em>)<a class="headerlink" href="#django.test.Client.post" title="永久链接至目标">¶</a></dt>
<dd><p>在提供的 <code class="docutils literal notranslate"><span class="pre">path</span></code> 上发出一个 POST 请求，并返回一个 <code class="docutils literal notranslate"><span class="pre">Response</span></code> 对象，如下所述。</p>
<p><code class="docutils literal notranslate"><span class="pre">data</span></code> 字典中的键值对用于提交 POST 数据。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s1">&#39;/login/&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;fred&#39;</span><span class="p">,</span> <span class="s1">&#39;passwd&#39;</span><span class="p">:</span> <span class="s1">&#39;secret&#39;</span><span class="p">})</span>
</pre></div>
</div>
<p>......将产生对这个 URL 的 POST 请求：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">/</span><span class="n">login</span><span class="o">/</span>
</pre></div>
</div>
<p>......具有此 POST 数据：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">name</span><span class="o">=</span><span class="n">fred</span><span class="o">&amp;</span><span class="n">passwd</span><span class="o">=</span><span class="n">secret</span>
</pre></div>
</div>
<p>如果你提供 <em class="mimetype">application/json</em> 为 <code class="docutils literal notranslate"><span class="pre">content_type</span></code>，则如果 <code class="docutils literal notranslate"><span class="pre">data</span></code> 是一个字典、列表或元组时，使用 <a class="reference external" href="https://docs.python.org/3/library/json.html#json.dumps" title="(在 Python v3.10)"><code class="xref py py-func docutils literal notranslate"><span class="pre">json.dumps()</span></code></a> 进行序列化。序列化默认是通过 <a class="reference internal" href="../serialization.html#django.core.serializers.json.DjangoJSONEncoder" title="django.core.serializers.json.DjangoJSONEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">DjangoJSONEncoder</span></code></a>，可以通过为 <a class="reference internal" href="#django.test.Client" title="django.test.Client"><code class="xref py py-class docutils literal notranslate"><span class="pre">Client</span></code></a> 提供 <code class="docutils literal notranslate"><span class="pre">json_encoder</span></code> 参数覆盖。这个序列化也会发生在 <a class="reference internal" href="#django.test.Client.put" title="django.test.Client.put"><code class="xref py py-meth docutils literal notranslate"><span class="pre">put()</span></code></a>、<a class="reference internal" href="#django.test.Client.patch" title="django.test.Client.patch"><code class="xref py py-meth docutils literal notranslate"><span class="pre">patch()</span></code></a> 和 <a class="reference internal" href="#django.test.Client.delete" title="django.test.Client.delete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">delete()</span></code></a> 请求中。</p>
<p>如果你要提供任何其他的 <code class="docutils literal notranslate"><span class="pre">content_type</span></code> （例如 <em class="mimetype">text/xml</em> 用于 XML 有效载荷），使用HTTP <code class="docutils literal notranslate"><span class="pre">Content-Type</span></code> 头中的 <code class="docutils literal notranslate"><span class="pre">content_type</span></code>，<code class="docutils literal notranslate"><span class="pre">data</span></code> 的内容在 POST 请求中按原样发送。</p>
<p>如果你没有为 <code class="docutils literal notranslate"><span class="pre">content_type</span></code> 提供一个值，<code class="docutils literal notranslate"><span class="pre">data</span></code> 中的值将以 <em class="mimetype">multipart/form-data</em> 的内容类型进行传输。在这种情况下，<code class="docutils literal notranslate"><span class="pre">data</span></code> 中的键值对将被编码为多部分消息，并用于创建 POST 数据有效载荷。</p>
<p>要为一个给定的键提交多个值——例如，要指定 <code class="docutils literal notranslate"><span class="pre">&lt;select</span> <span class="pre">multiple&gt;</span></code> 的选择——为所需键提供一个列表或元组的值。例如，这个 <code class="docutils literal notranslate"><span class="pre">data</span></code> 的值将为名为 <code class="docutils literal notranslate"><span class="pre">choices</span></code> 的字段提交三个选择值：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">{</span><span class="s1">&#39;choices&#39;</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;d&#39;</span><span class="p">)}</span>
</pre></div>
</div>
<p>提交文件是一种特殊情况。要 POST 一个文件，你只需要提供文件字段名作为键，以及你想上传的文件的文件句柄作为值。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;wishlist.doc&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">fp</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s1">&#39;/customers/wishes/&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;fred&#39;</span><span class="p">,</span> <span class="s1">&#39;attachment&#39;</span><span class="p">:</span> <span class="n">fp</span><span class="p">})</span>
</pre></div>
</div>
<p>（这里的 <code class="docutils literal notranslate"><span class="pre">attachment</span></code> 名称无关紧要；可以使用你的文件处理代码期望的任何名称。）</p>
<p>你也可以提供任何类似于文件的对象（例如 <a class="reference external" href="https://docs.python.org/3/library/io.html#io.StringIO" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> 或 <a class="reference external" href="https://docs.python.org/3/library/io.html#io.BytesIO" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">BytesIO</span></code></a>）作为文件句柄。如果你要上传到 <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ImageField" title="django.db.models.ImageField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImageField</span></code></a>，这个对象需要一个可以通过 <a class="reference internal" href="../../ref/validators.html#django.core.validators.validate_image_file_extension" title="django.core.validators.validate_image_file_extension"><code class="xref py py-data docutils literal notranslate"><span class="pre">validate_image_file_extension</span></code></a> 验证器的 <code class="docutils literal notranslate"><span class="pre">name</span></code> 属性。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">io</span> <span class="kn">import</span> <span class="n">BytesIO</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">img</span> <span class="o">=</span> <span class="n">BytesIO</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;mybinarydata&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">img</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s1">&#39;myimage.jpg&#39;</span>
</pre></div>
</div>
<p>请注意，如果你想在多次调用 <code class="docutils literal notranslate"><span class="pre">post()</span></code> 时使用同一个文件句柄，那么你需要在两次调用之间手动重置文件指针。最简单的方法是在向 <code class="docutils literal notranslate"><span class="pre">post()</span></code> 提供文件后手动关闭文件，如上所示。</p>
<p>你还应确保文件的打开方式允许数据被读取。如果你的文件包含二进制数据，如图像，这意味着你需要以 <code class="docutils literal notranslate"><span class="pre">rb</span></code> （读取二进制）模式打开文件。</p>
<p><code class="docutils literal notranslate"><span class="pre">extra</span></code> 参数的作用与 <a class="reference internal" href="#django.test.Client.get" title="django.test.Client.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Client.get()</span></code></a> 相同。</p>
<p>如果你用 POST 请求的 URL 包含编码参数，这些参数将在 request.GET 数据中提供。例如，如果你要请求：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s1">&#39;/login/?visitor=true&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;fred&#39;</span><span class="p">,</span> <span class="s1">&#39;passwd&#39;</span><span class="p">:</span> <span class="s1">&#39;secret&#39;</span><span class="p">})</span>
</pre></div>
</div>
<p>......处理这个请求的视图可以询问 request.POST 来检索用户名和密码，也可以询问 request.GET 来确定该用户是否是访客。</p>
<p>如果将 <code class="docutils literal notranslate"><span class="pre">follow</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，客户端将遵循所有重定向，并且将在响应对象中设置 <code class="docutils literal notranslate"><span class="pre">redirect_chain</span></code> 属性，该属性是包含中间 URL 和状态码的元组。</p>
<p>如果你把 <code class="docutils literal notranslate"><span class="pre">secure</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，则客户端将模拟 HTTPS 请求。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.Client.head">
<code class="descname">head</code>(<em>path</em>, <em>data=None</em>, <em>follow=False</em>, <em>secure=False</em>, <em>**extra</em>)<a class="headerlink" href="#django.test.Client.head" title="永久链接至目标">¶</a></dt>
<dd><p>在提供的 <code class="docutils literal notranslate"><span class="pre">path</span></code> 上发出一个 HEAD 请求，并返回一个 <code class="docutils literal notranslate"><span class="pre">Response</span></code> 对象。这个方法的工作原理和 <a class="reference internal" href="#django.test.Client.get" title="django.test.Client.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Client.get()</span></code></a>  一样，包括 <code class="docutils literal notranslate"><span class="pre">follow</span></code>、<code class="docutils literal notranslate"><span class="pre">secure</span></code> 和 <code class="docutils literal notranslate"><span class="pre">extra</span></code> 参数，只是它不返回消息主体。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.Client.options">
<code class="descname">options</code>(<em>path</em>, <em>data=''</em>, <em>content_type='application/octet-stream'</em>, <em>follow=False</em>, <em>secure=False</em>, <em>**extra</em>)<a class="headerlink" href="#django.test.Client.options" title="永久链接至目标">¶</a></dt>
<dd><p>在提供的 <code class="docutils literal notranslate"><span class="pre">path</span></code> 上发出一个 OPTIONS 请求并返回一个 <code class="docutils literal notranslate"><span class="pre">Response</span></code> 对象。用于测试 RESTful 接口。</p>
<p>当提供 <code class="docutils literal notranslate"><span class="pre">data</span></code> 时，它将被用作请求主体并且 <code class="docutils literal notranslate"><span class="pre">Content-Type</span></code> 头被设置为 <code class="docutils literal notranslate"><span class="pre">content_type</span></code>。</p>
<p><code class="docutils literal notranslate"><span class="pre">follow</span></code>、 <code class="docutils literal notranslate"><span class="pre">secure</span></code> 和 <code class="docutils literal notranslate"><span class="pre">extra</span></code> 参数的作用与 <a class="reference internal" href="#django.test.Client.get" title="django.test.Client.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Client.get()</span></code></a> 相同。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.Client.put">
<code class="descname">put</code>(<em>path</em>, <em>data=''</em>, <em>content_type='application/octet-stream'</em>, <em>follow=False</em>, <em>secure=False</em>, <em>**extra</em>)<a class="headerlink" href="#django.test.Client.put" title="永久链接至目标">¶</a></dt>
<dd><p>在提供的 <code class="docutils literal notranslate"><span class="pre">path</span></code> 上发出一个 PUT 请求，并返回一个 <code class="docutils literal notranslate"><span class="pre">Response</span></code> 对象。用于测试 RESTful 接口。</p>
<p>当提供 <code class="docutils literal notranslate"><span class="pre">data</span></code> 时，它将被用作请求主体并且 <code class="docutils literal notranslate"><span class="pre">Content-Type</span></code> 头被设置为 <code class="docutils literal notranslate"><span class="pre">content_type</span></code>。</p>
<p><code class="docutils literal notranslate"><span class="pre">follow</span></code>、 <code class="docutils literal notranslate"><span class="pre">secure</span></code> 和 <code class="docutils literal notranslate"><span class="pre">extra</span></code> 参数的作用与 <a class="reference internal" href="#django.test.Client.get" title="django.test.Client.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Client.get()</span></code></a> 相同。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.Client.patch">
<code class="descname">patch</code>(<em>path</em>, <em>data=''</em>, <em>content_type='application/octet-stream'</em>, <em>follow=False</em>, <em>secure=False</em>, <em>**extra</em>)<a class="headerlink" href="#django.test.Client.patch" title="永久链接至目标">¶</a></dt>
<dd><p>在提供的 <code class="docutils literal notranslate"><span class="pre">path</span></code> 上发出一个 PATCH 请求，并返回一个 <code class="docutils literal notranslate"><span class="pre">Response</span></code> 对象。用于测试 RESTful 接口。</p>
<p><code class="docutils literal notranslate"><span class="pre">follow</span></code>、 <code class="docutils literal notranslate"><span class="pre">secure</span></code> 和 <code class="docutils literal notranslate"><span class="pre">extra</span></code> 参数的作用与 <a class="reference internal" href="#django.test.Client.get" title="django.test.Client.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Client.get()</span></code></a> 相同。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.Client.delete">
<code class="descname">delete</code>(<em>path</em>, <em>data=''</em>, <em>content_type='application/octet-stream'</em>, <em>follow=False</em>, <em>secure=False</em>, <em>**extra</em>)<a class="headerlink" href="#django.test.Client.delete" title="永久链接至目标">¶</a></dt>
<dd><p>在提供的 <code class="docutils literal notranslate"><span class="pre">path</span></code> 上发出一个 DELETE 请求，并返回一个 <code class="docutils literal notranslate"><span class="pre">Response</span></code> 对象。用于测试 RESTful 接口。</p>
<p>当提供 <code class="docutils literal notranslate"><span class="pre">data</span></code> 时，它将被用作请求主体并且 <code class="docutils literal notranslate"><span class="pre">Content-Type</span></code> 头被设置为 <code class="docutils literal notranslate"><span class="pre">content_type</span></code>。</p>
<p><code class="docutils literal notranslate"><span class="pre">follow</span></code>、 <code class="docutils literal notranslate"><span class="pre">secure</span></code> 和 <code class="docutils literal notranslate"><span class="pre">extra</span></code> 参数的作用与 <a class="reference internal" href="#django.test.Client.get" title="django.test.Client.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Client.get()</span></code></a> 相同。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.Client.trace">
<code class="descname">trace</code>(<em>path</em>, <em>follow=False</em>, <em>secure=False</em>, <em>**extra</em>)<a class="headerlink" href="#django.test.Client.trace" title="永久链接至目标">¶</a></dt>
<dd><p>在提供的 <code class="docutils literal notranslate"><span class="pre">path</span></code> 上发出一个 TRACE 请求，并返回一个 <code class="docutils literal notranslate"><span class="pre">Response</span></code> 对象。用于模拟诊断探针。</p>
<p>与其他请求方法不同，为了符合 <span class="target" id="index-6"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7231.html#section-4.3.8"><strong>RFC 7231#section-4.3.8</strong></a> 的要求，不提供 <code class="docutils literal notranslate"><span class="pre">data</span></code> 作为关键字参数，该 RFC 要求跟踪请求不能有主体。</p>
<p><code class="docutils literal notranslate"><span class="pre">follow</span></code>、 <code class="docutils literal notranslate"><span class="pre">secure</span></code> 和 <code class="docutils literal notranslate"><span class="pre">extra</span></code> 参数的作用与 <a class="reference internal" href="#django.test.Client.get" title="django.test.Client.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Client.get()</span></code></a> 相同。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.Client.login">
<code class="descname">login</code>(<em>**credentials</em>)<a class="headerlink" href="#django.test.Client.login" title="永久链接至目标">¶</a></dt>
<dd><p>如果你的网站使用了 Django 的 <a class="reference internal" href="../auth/index.html"><span class="doc">认证系统</span></a>，并且你需要处理登录用户的问题，你可以使用测试客户端的 <code class="docutils literal notranslate"><span class="pre">login()</span></code> 方法来模拟用户登录网站的效果。</p>
<p>调用此方法后，测试客户端将拥有通过任何可能构成视图一部分的基于登录的测试所需的所有 cookie 和会话数据。</p>
<p><code class="docutils literal notranslate"><span class="pre">credentials</span></code> 参数的格式取决于你使用的 <a class="reference internal" href="../auth/customizing.html#authentication-backends"><span class="std std-ref">认证后端</span></a> （这是由你的 <a class="reference internal" href="../../ref/settings.html#std:setting-AUTHENTICATION_BACKENDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTHENTICATION_BACKENDS</span></code></a> 配置）。如果你使用的是 Django 提供的标准认证后端（<code class="docutils literal notranslate"><span class="pre">ModelBackend</span></code>），<code class="docutils literal notranslate"><span class="pre">credentials</span></code> 应该是用户的用户名和密码，并作为关键字参数提供：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">login</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s1">&#39;fred&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s1">&#39;secret&#39;</span><span class="p">)</span>

<span class="go"># Now you can access a view that&#39;s only available to logged-in users.</span>
</pre></div>
</div>
<p>如果你使用的是不同的认证后端，这个方法可能需要不同的凭证。它需要你的后端 <code class="docutils literal notranslate"><span class="pre">authenticate()</span></code> 方法所需要的任何凭证。</p>
<p>如果凭证被接受且登录成功，则 <code class="docutils literal notranslate"><span class="pre">login()</span></code> 返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>。</p>
<p>最后，在使用这个方法之前，你需要记得创建用户账户。正如我们上面所解释的，测试运行器是使用测试数据库执行的，默认情况下，数据库中不包含用户。因此，在生产站点上有效的用户账户在测试条件下将无法工作。你需要创建用户作为测试套件的一部分--无论是手动创建（使用 Django 模型 API）还是使用测试夹具。记住，如果你想让你的测试用户有一个密码，你不能直接通过设置密码属性来设置用户的密码——你必须使用 <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.set_password" title="django.contrib.auth.models.User.set_password"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_password()</span></code></a> 函数来存储一个正确的哈希密码。或者，你可以使用 <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.UserManager.create_user" title="django.contrib.auth.models.UserManager.create_user"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create_user()</span></code></a> 辅助方法来创建一个具有正确哈希密码的新用户。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.Client.force_login">
<code class="descname">force_login</code>(<em>user</em>, <em>backend=None</em>)<a class="headerlink" href="#django.test.Client.force_login" title="永久链接至目标">¶</a></dt>
<dd><p>如果你的网站使用了 Django 的 <a class="reference internal" href="../auth/index.html"><span class="doc">认证系统</span></a>，你可以使用 <code class="docutils literal notranslate"><span class="pre">force_login()</span></code> 方法来模拟用户登录网站的效果。当测试需要用户登录，而用户如何登录的细节并不重要时，可以使用这个方法代替 <a class="reference internal" href="#django.test.Client.login" title="django.test.Client.login"><code class="xref py py-meth docutils literal notranslate"><span class="pre">login()</span></code></a>。</p>
<p>与 <code class="docutils literal notranslate"><span class="pre">login()</span></code> 不同的是，这个方法跳过了认证和验证步骤：不活跃的用户（<a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.is_active" title="django.contrib.auth.models.User.is_active"><code class="xref py py-attr docutils literal notranslate"><span class="pre">is_active=False</span></code></a>）被允许登录，并且不需要提供用户凭证。</p>
<p>用户的 <code class="docutils literal notranslate"><span class="pre">backend</span></code> 属性将被设置为 <code class="docutils literal notranslate"><span class="pre">backend</span></code> 参数的值（应该是一个点分隔 Python 路径字符串），如果没有提供值，则设置为 <code class="docutils literal notranslate"><span class="pre">settings.AUTHENTICATION_BACKENDS[0]</span></code>。<a class="reference internal" href="#django.test.Client.login" title="django.test.Client.login"><code class="xref py py-meth docutils literal notranslate"><span class="pre">login()</span></code></a> 调用的 <a class="reference internal" href="../auth/default.html#django.contrib.auth.authenticate" title="django.contrib.auth.authenticate"><code class="xref py py-func docutils literal notranslate"><span class="pre">authenticate()</span></code></a> 函数通常会对用户进行注释。</p>
<p>这个方法比 <code class="docutils literal notranslate"><span class="pre">login()</span></code> 快，因为它绕过了昂贵的密码散列算法。另外，你也可以通过 <a class="reference internal" href="overview.html#speeding-up-tests-auth-hashers"><span class="std std-ref">在测试时使用较弱的哈希算法</span></a> 来加快 <code class="docutils literal notranslate"><span class="pre">login()</span></code> 速度。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.Client.logout">
<code class="descname">logout</code>()<a class="headerlink" href="#django.test.Client.logout" title="永久链接至目标">¶</a></dt>
<dd><p>如果你的网站使用了 Django 的 <a class="reference internal" href="../auth/index.html"><span class="doc">认证系统</span></a>，<code class="docutils literal notranslate"><span class="pre">logout()</span></code> 方法可以用来模拟用户注销网站的效果。</p>
<p>调用此方法后，测试客户端的所有 cookie 和会话数据都会被清除为默认值。随后的请求将看起来来自一个 <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.AnonymousUser" title="django.contrib.auth.models.AnonymousUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AnonymousUser</span></code></a>。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-testing-responses">
<span id="testing-responses"></span><h3>测试响应<a class="headerlink" href="#testing-responses" title="永久链接至标题">¶</a></h3>
<p><code class="docutils literal notranslate"><span class="pre">get()</span></code> 和 <code class="docutils literal notranslate"><span class="pre">post()</span></code> 方法都会返回一个 <code class="docutils literal notranslate"><span class="pre">Response</span></code> 对象，这个 <code class="docutils literal notranslate"><span class="pre">Response</span></code> 对象与 Django 视图返回的 <code class="docutils literal notranslate"><span class="pre">HttpResponse</span></code> 对象是 <em>不</em> 一样的；测试响应对象有一些额外的数据，对测试代码验证很有用。</p>
<p>具体来说，<code class="docutils literal notranslate"><span class="pre">Response</span></code> 对象具有以下属性：</p>
<dl class="class">
<dt id="django.test.Response">
<em class="property">class </em><code class="descname">Response</code><a class="headerlink" href="#django.test.Response" title="永久链接至目标">¶</a></dt>
<dd><dl class="attribute">
<dt id="django.test.Response.client">
<code class="descname">client</code><a class="headerlink" href="#django.test.Response.client" title="永久链接至目标">¶</a></dt>
<dd><p>用于发出请求并得到响应的测试客户端。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.test.Response.content">
<code class="descname">content</code><a class="headerlink" href="#django.test.Response.content" title="永久链接至目标">¶</a></dt>
<dd><p>以字节字符串形式的响应主体。 这是视图或任何错误消息所呈现的最终页面内容。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.test.Response.context">
<code class="descname">context</code><a class="headerlink" href="#django.test.Response.context" title="永久链接至目标">¶</a></dt>
<dd><p>模板 <code class="docutils literal notranslate"><span class="pre">Context</span></code> 实例，用于渲染产生响应内容的模板。</p>
<p>如果渲染的页面使用了多个模板，那么 <code class="docutils literal notranslate"><span class="pre">context</span></code> 将是一个按渲染顺序排列的 <code class="docutils literal notranslate"><span class="pre">Context</span></code> 对象列表。</p>
<p>无论在渲染过程中使用了多少模板，你都可以使用 <code class="docutils literal notranslate"><span class="pre">[]</span></code> 操作符来检索上下文值。例如，上下文变量 <code class="docutils literal notranslate"><span class="pre">name</span></code> 可以使用：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/foo/&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">response</span><span class="o">.</span><span class="n">context</span><span class="p">[</span><span class="s1">&#39;name&#39;</span><span class="p">]</span>
<span class="go">&#39;Arthur&#39;</span>
</pre></div>
</div>
<div class="admonition-not-using-django-templates admonition">
<p class="first admonition-title">没有使用 Django 模板？</p>
<p class="last">这个属性只有在使用 <a class="reference internal" href="../templates.html#django.template.backends.django.DjangoTemplates" title="django.template.backends.django.DjangoTemplates"><code class="xref py py-class docutils literal notranslate"><span class="pre">DjangoTemplates</span></code></a> 后端时才会被填充。如果你正在使用其他模板引擎，在带有该属性的响应上，<a class="reference internal" href="../../ref/template-response.html#django.template.response.SimpleTemplateResponse.context_data" title="django.template.response.SimpleTemplateResponse.context_data"><code class="xref py py-attr docutils literal notranslate"><span class="pre">context_data</span></code></a> 可能是一个合适的选择。</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="django.test.Response.exc_info">
<code class="descname">exc_info</code><a class="headerlink" href="#django.test.Response.exc_info" title="永久链接至目标">¶</a></dt>
<dd><p>一个由三个值组成的元组，它提供了关于在视图期间发生的未处理异常（如果有）的信息。</p>
<p>值是（type，value，traceback），与 Python 的 <a class="reference external" href="https://docs.python.org/3/library/sys.html#sys.exc_info" title="(在 Python v3.10)"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a> 返回的值相同。它们的含义是：</p>
<ul class="simple">
<li><em>type</em>：异常的类型。</li>
<li><em>value</em>：异常的实例。</li>
<li><em>traceback</em>：一个追溯对象，在最初发生异常的地方封装了调用堆栈。</li>
</ul>
<p>如果没有发生异常，那么 <code class="docutils literal notranslate"><span class="pre">exc_info</span></code> 将是 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.Response.json">
<code class="descname">json</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.test.Response.json" title="永久链接至目标">¶</a></dt>
<dd><p>解析为 JSON 的响应主体。额外的关键字参数传递给 <a class="reference external" href="https://docs.python.org/3/library/json.html#json.loads" title="(在 Python v3.10)"><code class="xref py py-func docutils literal notranslate"><span class="pre">json.loads()</span></code></a>。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/foo/&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">response</span><span class="o">.</span><span class="n">json</span><span class="p">()[</span><span class="s1">&#39;name&#39;</span><span class="p">]</span>
<span class="go">&#39;Arthur&#39;</span>
</pre></div>
</div>
<p>如果 <code class="docutils literal notranslate"><span class="pre">Content-Type</span></code> 头不是 <code class="docutils literal notranslate"><span class="pre">&quot;application/json&quot;</span></code>，那么在试图解析响应时将会出现一个 <a class="reference external" href="https://docs.python.org/3/library/exceptions.html#ValueError" title="(在 Python v3.10)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.test.Response.request">
<code class="descname">request</code><a class="headerlink" href="#django.test.Response.request" title="永久链接至目标">¶</a></dt>
<dd><p>激发响应的请求数据。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.test.Response.wsgi_request">
<code class="descname">wsgi_request</code><a class="headerlink" href="#django.test.Response.wsgi_request" title="永久链接至目标">¶</a></dt>
<dd><p>由生成响应的测试处理程序生成的 <code class="docutils literal notranslate"><span class="pre">WSGIRequest</span></code> 实例。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.test.Response.status_code">
<code class="descname">status_code</code><a class="headerlink" href="#django.test.Response.status_code" title="永久链接至目标">¶</a></dt>
<dd><p>整数形式的响应 HTTP 状态。关于定义代码的完整列表，查看 <a class="reference external" href="https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml">IANA status code registry</a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="django.test.Response.templates">
<code class="descname">templates</code><a class="headerlink" href="#django.test.Response.templates" title="永久链接至目标">¶</a></dt>
<dd><p>用于渲染最终内容的 <code class="docutils literal notranslate"><span class="pre">Template</span></code> 实例列表，按渲染顺序排列。对于列表中的每个模板，如果模板是从文件中加载的，则使用 <code class="docutils literal notranslate"><span class="pre">template.name</span></code> 获得模板的文件名。（名字是一个字符串，如 <code class="docutils literal notranslate"><span class="pre">'admin/index.html'</span></code>。）</p>
<div class="admonition-not-using-django-templates admonition">
<p class="first admonition-title">没有使用 Django 模板？</p>
<p class="last">这个属性只有在使用 <a class="reference internal" href="../templates.html#django.template.backends.django.DjangoTemplates" title="django.template.backends.django.DjangoTemplates"><code class="xref py py-class docutils literal notranslate"><span class="pre">DjangoTemplates</span></code></a> 后端时才会被填充。如果你使用的是其他模板引擎，并且你只需要渲染所用模板的名称，那么 <a class="reference internal" href="../../ref/template-response.html#django.template.response.SimpleTemplateResponse.template_name" title="django.template.response.SimpleTemplateResponse.template_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">template_name</span></code></a> 可能是一个合适的选择。</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="django.test.Response.resolver_match">
<code class="descname">resolver_match</code><a class="headerlink" href="#django.test.Response.resolver_match" title="永久链接至目标">¶</a></dt>
<dd><p>响应的 <a class="reference internal" href="../../ref/urlresolvers.html#django.urls.ResolverMatch" title="django.urls.ResolverMatch"><code class="xref py py-class docutils literal notranslate"><span class="pre">ResolverMatch</span></code></a> 的实例。你可以使用 <a class="reference internal" href="../../ref/urlresolvers.html#django.urls.ResolverMatch.func" title="django.urls.ResolverMatch.func"><code class="xref py py-attr docutils literal notranslate"><span class="pre">func</span></code></a> 属性，例如，验证服务于响应的视图：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># my_view here is a function based view</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">resolver_match</span><span class="o">.</span><span class="n">func</span><span class="p">,</span> <span class="n">my_view</span><span class="p">)</span>

<span class="c1"># class-based views need to be compared by name, as the functions</span>
<span class="c1"># generated by as_view() won&#39;t be equal</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">resolver_match</span><span class="o">.</span><span class="n">func</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">MyView</span><span class="o">.</span><span class="n">as_view</span><span class="p">()</span><span class="o">.</span><span class="vm">__name__</span><span class="p">)</span>
</pre></div>
</div>
<p>如果找不到给定的 URL，访问这个属性会引发一个 <a class="reference internal" href="../../ref/exceptions.html#django.urls.Resolver404" title="django.urls.Resolver404"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Resolver404</span></code></a> 异常。</p>
</dd></dl>

</dd></dl>

<p>和普通的响应一样，你也可以通过 <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse.headers" title="django.http.HttpResponse.headers"><code class="xref py py-attr docutils literal notranslate"><span class="pre">HttpResponse.headers</span></code></a> 访问头信息。例如，你可以使用 <code class="docutils literal notranslate"><span class="pre">response.headers['Content-Type']</span></code> 来确定一个响应的内容类型。</p>
</div>
<div class="section" id="s-exceptions">
<span id="exceptions"></span><h3>例外<a class="headerlink" href="#exceptions" title="永久链接至标题">¶</a></h3>
<p>如果你把测试客户端指向一个会引发异常的视图，并且 <code class="docutils literal notranslate"><span class="pre">Client.raise_request_exception</span></code> 是 <code class="docutils literal notranslate"><span class="pre">True</span></code>，那么这个异常将在测试用例中可见。然后你可以使用标准的 <code class="docutils literal notranslate"><span class="pre">try</span> <span class="pre">...</span> <span class="pre">except</span></code> 块或 <a class="reference external" href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises" title="(在 Python v3.10)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRaises()</span></code></a> 来测试异常。</p>
<p>测试客户端看不到的异常只有 <a class="reference internal" href="../http/views.html#django.http.Http404" title="django.http.Http404"><code class="xref py py-class docutils literal notranslate"><span class="pre">Http404</span></code></a>、<a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.PermissionDenied" title="django.core.exceptions.PermissionDenied"><code class="xref py py-class docutils literal notranslate"><span class="pre">PermissionDenied</span></code></a>、<a class="reference external" href="https://docs.python.org/3/library/exceptions.html#SystemExit" title="(在 Python v3.10)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> 和 <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.SuspiciousOperation" title="django.core.exceptions.SuspiciousOperation"><code class="xref py py-class docutils literal notranslate"><span class="pre">SuspiciousOperation</span></code></a>。Django 在内部捕获这些异常，并将其转换为相应的 HTTP 响应代码。在这些情况下，你可以在测试中检查 <code class="docutils literal notranslate"><span class="pre">response.status_code</span></code>。</p>
<p>如果 <code class="docutils literal notranslate"><span class="pre">Client.raise_request_exception</span></code> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code>，测试客户端将返回一个 500 的响应，就像返回给浏览器一样。响应有属性 <a class="reference internal" href="#django.test.Response.exc_info" title="django.test.Response.exc_info"><code class="xref py py-attr docutils literal notranslate"><span class="pre">exc_info</span></code></a> 来提供关于未处理的异常的信息。</p>
</div>
<div class="section" id="s-persistent-state">
<span id="persistent-state"></span><h3>持久状态<a class="headerlink" href="#persistent-state" title="永久链接至标题">¶</a></h3>
<p>测试客户端是有状态的。如果一个响应返回一个 cookie，那么这个 cookie 将被存储在测试客户端，并与所有后续的 <code class="docutils literal notranslate"><span class="pre">get()</span></code> 和 <code class="docutils literal notranslate"><span class="pre">post()</span></code> 请求一起发送。</p>
<p>不遵循这些 cookie 的过期策略。如果你希望 cookie 过期，请手动删除它或创建一个新的 <code class="docutils literal notranslate"><span class="pre">Client</span></code> 实例（这将有效地删除所有 cookie）。</p>
<p>测试客户端有两个属性，存储持久化的状态信息。你可以作为测试条件的一部分来访问这些属性。</p>
<dl class="attribute">
<dt id="django.test.Client.cookies">
<code class="descclassname">Client.</code><code class="descname">cookies</code><a class="headerlink" href="#django.test.Client.cookies" title="永久链接至目标">¶</a></dt>
<dd><p>一个 Python <a class="reference external" href="https://docs.python.org/3/library/http.cookies.html#http.cookies.SimpleCookie" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleCookie</span></code></a> 对象，包含所有客户端 cookie 的当前值。更多信息请参见 <a class="reference external" href="https://docs.python.org/3/library/http.cookies.html#module-http.cookies" title="(在 Python v3.10)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">http.cookies</span></code></a> 模块的文档。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.test.Client.session">
<code class="descclassname">Client.</code><code class="descname">session</code><a class="headerlink" href="#django.test.Client.session" title="永久链接至目标">¶</a></dt>
<dd><p>一个类似字典的对象，包含会话信息。详细内容请参见 <a class="reference internal" href="../http/sessions.html"><span class="doc">会话文档</span></a>。</p>
<p>要修改会话然后保存，必须先将其存储在一个变量中（因为每次访问该属性时都会创建一个新的 <code class="docutils literal notranslate"><span class="pre">SessionStore</span></code>）：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">test_something</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="n">session</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">session</span>
    <span class="n">session</span><span class="p">[</span><span class="s1">&#39;somekey&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;test&#39;</span>
    <span class="n">session</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="s-setting-the-language">
<span id="setting-the-language"></span><h3>设置语言<a class="headerlink" href="#setting-the-language" title="永久链接至标题">¶</a></h3>
<p>在测试支持国际化和本地化的应用程序时，你可能想为测试客户端请求设置语言。这样做的方法取决于 <a class="reference internal" href="../../ref/middleware.html#django.middleware.locale.LocaleMiddleware" title="django.middleware.locale.LocaleMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">LocaleMiddleware</span></code></a> 是否启用。</p>
<p>如果启用了中间件，可以通过创建一个名为 <a class="reference internal" href="../../ref/settings.html#std:setting-LANGUAGE_COOKIE_NAME"><code class="xref std std-setting docutils literal notranslate"><span class="pre">LANGUAGE_COOKIE_NAME</span></code></a> 的 cookie 来设置语言，其值为语言代码：。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>

<span class="k">def</span> <span class="nf">test_language_using_cookie</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">cookies</span><span class="o">.</span><span class="n">load</span><span class="p">({</span><span class="n">settings</span><span class="o">.</span><span class="n">LANGUAGE_COOKIE_NAME</span><span class="p">:</span> <span class="s1">&#39;fr&#39;</span><span class="p">})</span>
    <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/&#39;</span><span class="p">)</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">content</span><span class="p">,</span> <span class="sa">b</span><span class="s2">&quot;Bienvenue sur mon site.&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>或在请求中加入 <code class="docutils literal notranslate"><span class="pre">Accept-Language</span></code> HTTP 头：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">test_language_using_header</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/&#39;</span><span class="p">,</span> <span class="n">HTTP_ACCEPT_LANGUAGE</span><span class="o">=</span><span class="s1">&#39;fr&#39;</span><span class="p">)</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">content</span><span class="p">,</span> <span class="sa">b</span><span class="s2">&quot;Bienvenue sur mon site.&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>更多细节请参考 <a class="reference internal" href="../i18n/translation.html#how-django-discovers-language-preference"><span class="std std-ref">Django 如何发现语言偏好</span></a>。</p>
<p>如果中间件没有启用，可以使用 <a class="reference internal" href="../../ref/utils.html#django.utils.translation.override" title="django.utils.translation.override"><code class="xref py py-func docutils literal notranslate"><span class="pre">translation.override()</span></code></a> 设置活动语言：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">translation</span>

<span class="k">def</span> <span class="nf">test_language_using_override</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="k">with</span> <span class="n">translation</span><span class="o">.</span><span class="n">override</span><span class="p">(</span><span class="s1">&#39;fr&#39;</span><span class="p">):</span>
        <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/&#39;</span><span class="p">)</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">content</span><span class="p">,</span> <span class="sa">b</span><span class="s2">&quot;Bienvenue sur mon site.&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>更多细节见 <a class="reference internal" href="../i18n/translation.html#explicitly-setting-the-active-language"><span class="std std-ref">显式设置语言</span></a>。</p>
</div>
<div class="section" id="s-example">
<span id="example"></span><h3>例如<a class="headerlink" href="#example" title="永久链接至标题">¶</a></h3>
<p>以下是使用测试客户端进行的单元测试：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">unittest</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">Client</span>

<span class="k">class</span> <span class="nc">SimpleTest</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Every test needs a client.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">client</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">test_details</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Issue a GET request.</span>
        <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/customer/details/&#39;</span><span class="p">)</span>

        <span class="c1"># Check that the response is 200 OK.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>

        <span class="c1"># Check that the rendered context contains 5 customers.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">context</span><span class="p">[</span><span class="s1">&#39;customers&#39;</span><span class="p">]),</span> <span class="mi">5</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last"><a class="reference internal" href="advanced.html#django.test.RequestFactory" title="django.test.RequestFactory"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.test.RequestFactory</span></code></a></p>
</div>
</div>
</div>
<div class="section" id="s-provided-test-case-classes">
<span id="s-django-testcase-subclasses"></span><span id="provided-test-case-classes"></span><span id="django-testcase-subclasses"></span><h2>提供的测试用例类<a class="headerlink" href="#provided-test-case-classes" title="永久链接至标题">¶</a></h2>
<p>一般的 Python 单元测试类都会扩展一个基类 <a class="reference external" href="https://docs.python.org/3/library/unittest.html#unittest.TestCase" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestCase</span></code></a>。Django 提供了这个基类的一些扩展。</p>
<div class="figure" id="id4">
<span id="testcase-hierarchy-diagram"></span><a class="reference internal image-reference" href="../../_images/django_unittest_classes_hierarchy.svg"><img alt="Hierarchy of Django unit testing classes (TestCase subclasses)" height="328" src="../../_images/django_unittest_classes_hierarchy.svg" width="508" /></a>
<p class="caption"><span class="caption-text">Django 单元测试类的层次结构</span></p>
</div>
<p>你可以将一个普通的 <a class="reference external" href="https://docs.python.org/3/library/unittest.html#unittest.TestCase" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestCase</span></code></a> 转换为任何一个子类：将你的测试基类从 <code class="docutils literal notranslate"><span class="pre">unittest.TestCase</span></code> 改为子类。所有标准的 Python 单元测试功能都将是可用的，并且它将被一些有用的附加功能所增强，如下面每节所述。</p>
<div class="section" id="s-simpletestcase">
<span id="simpletestcase"></span><h3><code class="docutils literal notranslate"><span class="pre">SimpleTestCase</span></code><a class="headerlink" href="#simpletestcase" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.test.SimpleTestCase">
<em class="property">class </em><code class="descname">SimpleTestCase</code><a class="headerlink" href="#django.test.SimpleTestCase" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><a class="reference external" href="https://docs.python.org/3/library/unittest.html#unittest.TestCase" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestCase</span></code></a> 的一个子类，增加了以下功能：</p>
<ul class="simple">
<li>一些有用的断言，例如：<ul>
<li>检查一个可调用对象 <a class="reference internal" href="#django.test.SimpleTestCase.assertRaisesMessage" title="django.test.SimpleTestCase.assertRaisesMessage"><code class="xref py py-meth docutils literal notranslate"><span class="pre">会引发某个异常</span></code></a>。</li>
<li>检查一个可调用对象 <a class="reference internal" href="#django.test.SimpleTestCase.assertWarnsMessage" title="django.test.SimpleTestCase.assertWarnsMessage"><code class="xref py py-meth docutils literal notranslate"><span class="pre">会触发某个警告</span></code></a>。</li>
<li>测试表单字段 <a class="reference internal" href="#django.test.SimpleTestCase.assertFieldOutput" title="django.test.SimpleTestCase.assertFieldOutput"><code class="xref py py-meth docutils literal notranslate"><span class="pre">渲染和错误处理</span></code></a>。</li>
<li>测试 <a class="reference internal" href="#django.test.SimpleTestCase.assertContains" title="django.test.SimpleTestCase.assertContains"><code class="xref py py-meth docutils literal notranslate"><span class="pre">HTML</span> <span class="pre">响应是否存在／缺乏给定的片段</span></code></a>。</li>
<li>验证模板 <a class="reference internal" href="#django.test.SimpleTestCase.assertTemplateUsed" title="django.test.SimpleTestCase.assertTemplateUsed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">是否被用于生成给定的响应内容</span></code></a>。</li>
<li>验证两个 <a class="reference internal" href="#django.test.SimpleTestCase.assertURLEqual" title="django.test.SimpleTestCase.assertURLEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">URL</span></code></a> 是否相等。</li>
<li>验证一个 HTTP <a class="reference internal" href="#django.test.SimpleTestCase.assertRedirects" title="django.test.SimpleTestCase.assertRedirects"><code class="xref py py-meth docutils literal notranslate"><span class="pre">重定向</span></code></a> 是由应用执行的。</li>
<li>严格测试两个 <a class="reference internal" href="#django.test.SimpleTestCase.assertHTMLEqual" title="django.test.SimpleTestCase.assertHTMLEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">HTML</span> <span class="pre">片段</span></code></a> 是否相等或 <a class="reference internal" href="#django.test.SimpleTestCase.assertInHTML" title="django.test.SimpleTestCase.assertInHTML"><code class="xref py py-meth docutils literal notranslate"><span class="pre">包含</span></code></a>。</li>
<li>严格测试两个 <a class="reference internal" href="#django.test.SimpleTestCase.assertXMLEqual" title="django.test.SimpleTestCase.assertXMLEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">XML</span> <span class="pre">片段</span></code></a> 是否相等。</li>
<li>严格测试两个 <a class="reference internal" href="#django.test.SimpleTestCase.assertJSONEqual" title="django.test.SimpleTestCase.assertJSONEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">JSON</span> <span class="pre">片段</span></code></a> 相等。</li>
</ul>
</li>
<li>能够用 <a class="reference internal" href="#overriding-settings"><span class="std std-ref">修改后的配置</span></a> 运行测试。</li>
<li>使用 <a class="reference internal" href="#django.test.SimpleTestCase.client" title="django.test.SimpleTestCase.client"><code class="xref py py-attr docutils literal notranslate"><span class="pre">client</span></code></a> <a class="reference internal" href="#django.test.Client" title="django.test.Client"><code class="xref py py-class docutils literal notranslate"><span class="pre">Client</span></code></a>。</li>
</ul>
<p>如果你的测试进行任何数据库查询，请使用子类 <a class="reference internal" href="#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TransactionTestCase</span></code></a> 或 <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>。</p>
<dl class="attribute">
<dt id="django.test.SimpleTestCase.databases">
<code class="descclassname">SimpleTestCase.</code><code class="descname">databases</code><a class="headerlink" href="#django.test.SimpleTestCase.databases" title="永久链接至目标">¶</a></dt>
<dd><p><a class="reference internal" href="#django.test.SimpleTestCase" title="django.test.SimpleTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleTestCase</span></code></a> 默认不允许数据库查询。这有助于避免执行写查询而影响其他测试，因为每个 <code class="docutils literal notranslate"><span class="pre">SimpleTestCase</span></code> 测试不是在事务中运行的。如果你不关心这个问题，你可以通过在你的测试类上设置 <code class="docutils literal notranslate"><span class="pre">databases</span></code> 类属性为 <code class="docutils literal notranslate"><span class="pre">'__all__'</span></code> 来禁止这个行为。</p>
</dd></dl>

<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p><code class="docutils literal notranslate"><span class="pre">SimpleTestCase</span></code> 和它的子类（如 <code class="docutils literal notranslate"><span class="pre">TestCase</span></code>）依靠 <code class="docutils literal notranslate"><span class="pre">setUpClass()</span></code> 和 <code class="docutils literal notranslate"><span class="pre">tearDownClass()</span></code> 来执行一些全类范围的初始化（如覆盖配置）。如果你需要覆盖这些方法，别忘了调用 <code class="docutils literal notranslate"><span class="pre">super</span></code> 实现：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">setUpClass</span><span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">setUpClass</span><span class="p">()</span>
        <span class="o">...</span>

    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">tearDownClass</span><span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
        <span class="o">...</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">tearDownClass</span><span class="p">()</span>
</pre></div>
</div>
<p class="last">如果在 <code class="docutils literal notranslate"><span class="pre">setUpClass()</span></code> 过程中出现异常，一定要考虑到 Python 的行为。如果发生这种情况，类中的测试和 <code class="docutils literal notranslate"><span class="pre">tearDownClass()</span></code> 都不会被运行。在 <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.test.TestCase</span></code></a> 的情况下，这将会泄露在 <code class="docutils literal notranslate"><span class="pre">super()</span></code> 中创建的事务，从而导致各种症状，包括在某些平台上的分段故障（在 macOS 上报告）。如果你想在 <code class="docutils literal notranslate"><span class="pre">setUpClass()</span></code> 中故意引发一个异常，如 <a class="reference external" href="https://docs.python.org/3/library/unittest.html#unittest.SkipTest" title="(在 Python v3.10)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">unittest.SkipTest</span></code></a>，一定要在调用 <code class="docutils literal notranslate"><span class="pre">super()</span></code> 之前进行，以避免这种情况。</p>
</div>
<div class="versionchanged">
<span class="title">Changed in Django 3.1:</span> <p><code class="docutils literal notranslate"><span class="pre">debug()</span></code> 方法是为了允许在不收集结果和捕获异常的情况下运行测试。</p>
</div>
</div>
<div class="section" id="s-transactiontestcase">
<span id="transactiontestcase"></span><h3><code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code><a class="headerlink" href="#transactiontestcase" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.test.TransactionTestCase">
<em class="property">class </em><code class="descname">TransactionTestCase</code><a class="headerlink" href="#django.test.TransactionTestCase" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code> 继承自 <a class="reference internal" href="#django.test.SimpleTestCase" title="django.test.SimpleTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleTestCase</span></code></a> 以增加一些数据库特有的功能：</p>
<ul class="simple">
<li>在每次测试开始时将数据库重新设置为已知状态，以方便测试和使用 ORM。</li>
<li>数据库 <a class="reference internal" href="#django.test.TransactionTestCase.fixtures" title="django.test.TransactionTestCase.fixtures"><code class="xref py py-attr docutils literal notranslate"><span class="pre">fixtures</span></code></a>.</li>
<li>测试 <a class="reference internal" href="#skipping-tests"><span class="std std-ref">基于数据库后端功能的跳过</span></a>.</li>
<li>其他专门的 <a class="reference internal" href="#django.test.TransactionTestCase.assertQuerysetEqual" title="django.test.TransactionTestCase.assertQuerysetEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assert*</span></code></a> 方法。</li>
</ul>
<p>Django 的 <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> 类是 <code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code> 的一个比较常用的子类，它利用数据库事务设施来加快在每次测试开始时将数据库重置到已知状态的过程。然而，这样做的一个后果是，有些数据库行为不能在 Django <code class="docutils literal notranslate"><span class="pre">TestCase</span></code> 类中进行测试。例如，你不能像使用 <code class="xref py py-meth docutils literal notranslate"><span class="pre">select_for_update()</span></code> 时那样，测试一个代码块是否在一个事务中执行。在这些情况下，你应该使用 <code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code>。</p>
<p><code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code> 和 <code class="docutils literal notranslate"><span class="pre">TestCase</span></code> 除了将数据库重设为已知状态的方式和测试与测试提交和回滚效果的相关代码外，其他都是相同的。</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code> 在测试运行后，通过清空所有表来重置数据库。<code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code> 可以调用提交和回滚，并观察这些调用对数据库的影响。</li>
<li>另一方面，<code class="docutils literal notranslate"><span class="pre">TestCase</span></code> 在测试后不清空表。相反，它将测试代码包含在数据库事务中，在测试结束后回滚。这保证了测试结束时的回滚能将数据库恢复到初始状态。</li>
</ul>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p>在不支持回滚的数据库上运行的 <code class="docutils literal notranslate"><span class="pre">TestCase</span></code> （例如 MyISAM 存储引擎的 MySQL ），则 <code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code> 的所有实例，将在测试结束时回滚，删除测试数据库中的所有数据。</p>
<p class="last">应用 <a class="reference internal" href="overview.html#test-case-serialized-rollback"><span class="std std-ref">不会看到他们的数据被重新加载</span></a>；如果你需要这个功能（例如，第三方应用应该启用这个功能），你可以在 <code class="docutils literal notranslate"><span class="pre">TestCase</span></code> 中设置 <code class="docutils literal notranslate"><span class="pre">serialized_rollback</span> <span class="pre">=</span> <span class="pre">True</span></code>。</p>
</div>
</div>
<div class="section" id="s-testcase">
<span id="testcase"></span><h3><code class="docutils literal notranslate"><span class="pre">TestCase</span></code><a class="headerlink" href="#testcase" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.test.TestCase">
<em class="property">class </em><code class="descname">TestCase</code><a class="headerlink" href="#django.test.TestCase" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>这是 Django 中最常用的编写测试的类。它继承自 <a class="reference internal" href="#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TransactionTestCase</span></code></a> （以及扩展自 <a class="reference internal" href="#django.test.SimpleTestCase" title="django.test.SimpleTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleTestCase</span></code></a>）。如果你的 Django 应用程序不使用数据库，就使用 <a class="reference internal" href="#django.test.SimpleTestCase" title="django.test.SimpleTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleTestCase</span></code></a>。</p>
<p>此类：</p>
<ul class="simple">
<li>在两个嵌套的 <a class="reference internal" href="../db/transactions.html#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> 块中封装测试：一个用于整个类，一个用于每个测试。因此，如果你想测试一些特定的数据库事务行为，可以使用 <a class="reference internal" href="#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TransactionTestCase</span></code></a>。</li>
<li>在每次测试结束时检查可延迟的数据库约束。</li>
</ul>
<p>它还提供了另一种方法：</p>
<dl class="classmethod">
<dt id="django.test.TestCase.setUpTestData">
<em class="property">classmethod </em><code class="descclassname">TestCase.</code><code class="descname">setUpTestData</code>()<a class="headerlink" href="#django.test.TestCase.setUpTestData" title="永久链接至目标">¶</a></dt>
<dd><p>上文所述的类级 <code class="docutils literal notranslate"><span class="pre">atomic</span></code> 块允许在类级创建初始数据，整个 <code class="docutils literal notranslate"><span class="pre">TestCase</span></code> 只需一次。与使用 <code class="docutils literal notranslate"><span class="pre">setUp()</span></code> 相比，这种技术允许更快的测试。</p>
<p>例如:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span>

<span class="k">class</span> <span class="nc">MyTests</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">setUpTestData</span><span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
        <span class="c1"># Set up data for the whole TestCase</span>
        <span class="bp">cls</span><span class="o">.</span><span class="n">foo</span> <span class="o">=</span> <span class="n">Foo</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">bar</span><span class="o">=</span><span class="s2">&quot;Test&quot;</span><span class="p">)</span>
        <span class="o">...</span>

    <span class="k">def</span> <span class="nf">test1</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Some test using self.foo</span>
        <span class="o">...</span>

    <span class="k">def</span> <span class="nf">test2</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Some other test using self.foo</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>请注意，如果测试是在没有事务支持的数据库上运行（例如，MyISAM 引擎的 MySQL），<code class="docutils literal notranslate"><span class="pre">setUpTestData()</span></code> 将在每次测试前被调用，从而降低了速度优势。</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>在 <code class="docutils literal notranslate"><span class="pre">setUpTestData()</span></code> 中分配给类属性的对象必须支持用 <a class="reference external" href="https://docs.python.org/3/library/copy.html#copy.deepcopy" title="(在 Python v3.10)"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy.deepcopy()</span></code></a> 来创建深度拷贝，以便将它们与每个测试方法所做的改变隔离。在以前的 Django 版本中，这些对象被重复使用，对它们所做的改变在测试方法之间持续存在。</p>
</div>
</dd></dl>

<dl class="classmethod">
<dt id="django.test.TestCase.captureOnCommitCallbacks">
<em class="property">classmethod </em><code class="descclassname">TestCase.</code><code class="descname">captureOnCommitCallbacks</code>(<em>using=DEFAULT_DB_ALIAS</em>, <em>execute=False</em>)<a class="headerlink" href="#django.test.TestCase.captureOnCommitCallbacks" title="永久链接至目标">¶</a></dt>
<dd><div class="versionadded">
<span class="title">New in Django 3.2.</span> </div>
<p>返回一个为给定的数据库连接捕获 <a class="reference internal" href="../db/transactions.html#django.db.transaction.on_commit" title="django.db.transaction.on_commit"><code class="xref py py-func docutils literal notranslate"><span class="pre">transaction.on_commit()</span></code></a> 回调的上下文管理器。它返回一个列表，其中包含在退出上下文时，捕获的回调函数。从这个列表中，你可以对回调进行断言，或者调用它们来获得其副作用，模拟一个提交。</p>
<p><code class="docutils literal notranslate"><span class="pre">using</span></code> 是数据库连接的别名，用于捕获回调。</p>
<p>如果 <code class="docutils literal notranslate"><span class="pre">execute</span></code> 是 <code class="docutils literal notranslate"><span class="pre">True</span></code>，并且如果没有发生异常，所有的回调将在上下文管理器退出时被调用。这模拟了在包裹的代码块之后的提交。</p>
<p>例如:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> <span class="n">mail</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span>


<span class="k">class</span> <span class="nc">ContactTests</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_post</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">captureOnCommitCallbacks</span><span class="p">(</span><span class="n">execute</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="k">as</span> <span class="n">callbacks</span><span class="p">:</span>
            <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">post</span><span class="p">(</span>
                <span class="s1">&#39;/contact/&#39;</span><span class="p">,</span>
                <span class="p">{</span><span class="s1">&#39;message&#39;</span><span class="p">:</span> <span class="s1">&#39;I like your site&#39;</span><span class="p">},</span>
            <span class="p">)</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">callbacks</span><span class="p">),</span> <span class="mi">1</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">mail</span><span class="o">.</span><span class="n">outbox</span><span class="p">),</span> <span class="mi">1</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">mail</span><span class="o">.</span><span class="n">outbox</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">subject</span><span class="p">,</span> <span class="s1">&#39;Contact Form&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">mail</span><span class="o">.</span><span class="n">outbox</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">body</span><span class="p">,</span> <span class="s1">&#39;I like your site&#39;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="s-liveservertestcase">
<span id="s-live-test-server"></span><span id="liveservertestcase"></span><span id="live-test-server"></span><h3><code class="docutils literal notranslate"><span class="pre">LiveServerTestCase</span></code><a class="headerlink" href="#liveservertestcase" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.test.LiveServerTestCase">
<em class="property">class </em><code class="descname">LiveServerTestCase</code><a class="headerlink" href="#django.test.LiveServerTestCase" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">LiveServerTestCase</span></code> 和 <a class="reference internal" href="#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TransactionTestCase</span></code></a> 的功能基本相同，但多了一个功能：它在设置时在后台启动一个实时的 Django 服务器，并在关闭时将其关闭。这就允许使用 <a class="reference internal" href="#test-client"><span class="std std-ref">Django 虚拟客户端</span></a> 以外的自动化测试客户端，例如，<a class="reference external" href="https://www.selenium.dev/">Selenium</a> 客户端，在浏览器内执行一系列功能测试，并模拟真实用户的操作。</p>
<p>实时服务器在 <code class="docutils literal notranslate"><span class="pre">localhost</span></code> 上监听，并绑定到 0 号端口，0 号端口使用操作系统分配的一个空闲端口。在测试过程中可以用 <code class="docutils literal notranslate"><span class="pre">self.live_server_url</span></code> 访问服务器的 URL。</p>
<p>为了演示如何使用 <code class="docutils literal notranslate"><span class="pre">LiveServerTestCase</span></code>，让我们写一个 Selenium 测试。首先，你需要将 <a class="reference external" href="https://pypi.org/project/selenium/">selenium package</a> 安装到你的 Python 路径中。</p>
<div class="console-block" id="console-block-0">
<input class="c-tab-unix" id="c-tab-0-unix" type="radio" name="console-0" checked>
<label for="c-tab-0-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-0-win" type="radio" name="console-0">
<label for="c-tab-0-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-0-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python -m pip install selenium
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-0-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> py -m pip install selenium
</pre></div>
</section>
</div>
<p>然后，在你的应用程序的测试模块中添加一个基于 <code class="docutils literal notranslate"><span class="pre">LiveServerTestCase</span></code> 的测试（例如：<code class="docutils literal notranslate"><span class="pre">myapp/tests.py</span></code>）。在这个例子中，我们将假设你正在使用 <a class="reference internal" href="../../ref/contrib/staticfiles.html#module-django.contrib.staticfiles" title="django.contrib.staticfiles: An app for handling static files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">staticfiles</span></code></a> 应用，并且希望在执行测试时提供类似于我们在开发时使用 <code class="docutils literal notranslate"><span class="pre">DEBUG=True</span></code> 得到的静态文件，即不必使用 <a class="reference internal" href="../../ref/contrib/staticfiles.html#django-admin-collectstatic"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">collectstatic</span></code></a> 收集它们。我们将使用 <a class="reference internal" href="../../ref/contrib/staticfiles.html#django.contrib.staticfiles.testing.StaticLiveServerTestCase" title="django.contrib.staticfiles.testing.StaticLiveServerTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">StaticLiveServerTestCase</span></code></a> 子类，它提供了这个功能。如果不需要的话，可以用 <code class="docutils literal notranslate"><span class="pre">django.test.LiveServerTestCase</span></code> 代替。</p>
<p>这个测试的代码可能如下：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.staticfiles.testing</span> <span class="kn">import</span> <span class="n">StaticLiveServerTestCase</span>
<span class="kn">from</span> <span class="nn">selenium.webdriver.firefox.webdriver</span> <span class="kn">import</span> <span class="n">WebDriver</span>

<span class="k">class</span> <span class="nc">MySeleniumTests</span><span class="p">(</span><span class="n">StaticLiveServerTestCase</span><span class="p">):</span>
    <span class="n">fixtures</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;user-data.json&#39;</span><span class="p">]</span>

    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">setUpClass</span><span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">setUpClass</span><span class="p">()</span>
        <span class="bp">cls</span><span class="o">.</span><span class="n">selenium</span> <span class="o">=</span> <span class="n">WebDriver</span><span class="p">()</span>
        <span class="bp">cls</span><span class="o">.</span><span class="n">selenium</span><span class="o">.</span><span class="n">implicitly_wait</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>

    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">tearDownClass</span><span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
        <span class="bp">cls</span><span class="o">.</span><span class="n">selenium</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">tearDownClass</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">test_login</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">selenium</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%s%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">live_server_url</span><span class="p">,</span> <span class="s1">&#39;/login/&#39;</span><span class="p">))</span>
        <span class="n">username_input</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">selenium</span><span class="o">.</span><span class="n">find_element_by_name</span><span class="p">(</span><span class="s2">&quot;username&quot;</span><span class="p">)</span>
        <span class="n">username_input</span><span class="o">.</span><span class="n">send_keys</span><span class="p">(</span><span class="s1">&#39;myuser&#39;</span><span class="p">)</span>
        <span class="n">password_input</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">selenium</span><span class="o">.</span><span class="n">find_element_by_name</span><span class="p">(</span><span class="s2">&quot;password&quot;</span><span class="p">)</span>
        <span class="n">password_input</span><span class="o">.</span><span class="n">send_keys</span><span class="p">(</span><span class="s1">&#39;secret&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">selenium</span><span class="o">.</span><span class="n">find_element_by_xpath</span><span class="p">(</span><span class="s1">&#39;//input[@value=&quot;Log in&quot;]&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">click</span><span class="p">()</span>
</pre></div>
</div>
<p>最后，你可以按以下方式进行测试：</p>
<div class="console-block" id="console-block-1">
<input class="c-tab-unix" id="c-tab-1-unix" type="radio" name="console-1" checked>
<label for="c-tab-1-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-1-win" type="radio" name="console-1">
<label for="c-tab-1-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-1-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./manage.py <span class="nb">test</span> myapp.tests.MySeleniumTests.test_login
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-1-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> manage.py test myapp.tests.MySeleniumTests.test_login
</pre></div>
</section>
</div>
<p>这个例子会自动打开 Firefox，然后进入登录页面，输入凭证并按“登录”按钮。Selenium 提供了其他驱动程序，以防你没有安装 Firefox 或希望使用其他浏览器。上面的例子只是 Selenium 客户端能做的一小部分，更多细节请查看 <a class="reference external" href="https://selenium-python.readthedocs.io/api.html">full reference</a>。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p>当使用内存 SQLite 数据库运行测试时，同一个数据库连接将由两个线程并行共享：运行实时服务器的线程和运行测试用例的线程。要防止两个线程通过这个共享连接同时进行数据库查询，因为这有时可能会随机导致测试失败。所以你需要确保两个线程不会同时访问数据库。特别是，这意味着在某些情况下（例如，刚刚点击一个链接或提交一个表单之后），你可能需要检查 Selenium 是否收到了响应，并且在继续执行进一步的测试之前，检查下一个页面是否被加载。例如，让 Selenium 等待直到在响应中找到 <code class="docutils literal notranslate"><span class="pre">&lt;body&gt;</span></code> HTML 标签（需要 Selenium &gt; 2.13）：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">test_login</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="kn">from</span> <span class="nn">selenium.webdriver.support.wait</span> <span class="kn">import</span> <span class="n">WebDriverWait</span>
    <span class="n">timeout</span> <span class="o">=</span> <span class="mi">2</span>
    <span class="o">...</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">selenium</span><span class="o">.</span><span class="n">find_element_by_xpath</span><span class="p">(</span><span class="s1">&#39;//input[@value=&quot;Log in&quot;]&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">click</span><span class="p">()</span>
    <span class="c1"># Wait until the response is received</span>
    <span class="n">WebDriverWait</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">selenium</span><span class="p">,</span> <span class="n">timeout</span><span class="p">)</span><span class="o">.</span><span class="n">until</span><span class="p">(</span>
        <span class="k">lambda</span> <span class="n">driver</span><span class="p">:</span> <span class="n">driver</span><span class="o">.</span><span class="n">find_element_by_tag_name</span><span class="p">(</span><span class="s1">&#39;body&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p class="last">这里的棘手之处在于，实际上并不存在“页面加载”这样的事情，尤其是在现代 Web 应用程序中，服务器生成初始文档后会动态生成 HTML。因此，检查响应中是否存在 <code class="docutils literal notranslate"><span class="pre">&lt;body&gt;</span></code> 可能不一定适合所有的使用情况。请参考 <a class="reference external" href="https://web.archive.org/web/20160129132110/http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_WebDriver_fails_to_find_elements_/_Does_not_block_on_page_loa">Selenium FAQ</a> 和 <a class="reference external" href="https://www.selenium.dev/documentation/webdriver/waits/#explicit-wait">Selenium documentation</a> 了解更多信息。</p>
</div>
</div>
</div>
<div class="section" id="s-test-cases-features">
<span id="test-cases-features"></span><h2>测试用例特性<a class="headerlink" href="#test-cases-features" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-default-test-client">
<span id="default-test-client"></span><h3>默认测试客户端<a class="headerlink" href="#default-test-client" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.test.SimpleTestCase.client">
<code class="descclassname">SimpleTestCase.</code><code class="descname">client</code><a class="headerlink" href="#django.test.SimpleTestCase.client" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">django.test.*TestCase</span></code> 实例中的每个测试用例都可以访问一个 Django 测试客户端的实例。这个客户端可以用 <code class="docutils literal notranslate"><span class="pre">self.client</span></code> 来访问。这个客户端在每个测试中都会被重新创建，所以你不必担心状态（比如 cookie）会从一个测试转移到另一个测试中。</p>
<p>这意味着，不必每个测试中实例化一个 <code class="docutils literal notranslate"><span class="pre">Client</span></code>：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">unittest</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">Client</span>

<span class="k">class</span> <span class="nc">SimpleTest</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_details</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">client</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/customer/details/&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">test_index</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">client</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/customer/index/&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>
</pre></div>
</div>
<p>......你可以引用 <code class="docutils literal notranslate"><span class="pre">self.client</span></code>，像这样：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span>

<span class="k">class</span> <span class="nc">SimpleTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_details</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/customer/details/&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">test_index</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/customer/index/&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-customizing-the-test-client">
<span id="customizing-the-test-client"></span><h3>自定义测试客户端<a class="headerlink" href="#customizing-the-test-client" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.test.SimpleTestCase.client_class">
<code class="descclassname">SimpleTestCase.</code><code class="descname">client_class</code><a class="headerlink" href="#django.test.SimpleTestCase.client_class" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>如果你想使用不同的 <code class="docutils literal notranslate"><span class="pre">Client</span></code> 类（例如，一个具有自定义行为的子类），使用 <a class="reference internal" href="#django.test.SimpleTestCase.client_class" title="django.test.SimpleTestCase.client_class"><code class="xref py py-attr docutils literal notranslate"><span class="pre">client_class</span></code></a> 类属性：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">Client</span><span class="p">,</span> <span class="n">TestCase</span>

<span class="k">class</span> <span class="nc">MyTestClient</span><span class="p">(</span><span class="n">Client</span><span class="p">):</span>
    <span class="c1"># Specialized methods for your environment</span>
    <span class="o">...</span>

<span class="k">class</span> <span class="nc">MyTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="n">client_class</span> <span class="o">=</span> <span class="n">MyTestClient</span>

    <span class="k">def</span> <span class="nf">test_my_stuff</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Here self.client is an instance of MyTestClient...</span>
        <span class="n">call_some_test_code</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="s-fixture-loading">
<span id="s-topics-testing-fixtures"></span><span id="fixture-loading"></span><span id="topics-testing-fixtures"></span><h3>辅助工具加载<a class="headerlink" href="#fixture-loading" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.test.TransactionTestCase.fixtures">
<code class="descclassname">TransactionTestCase.</code><code class="descname">fixtures</code><a class="headerlink" href="#django.test.TransactionTestCase.fixtures" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>如果数据库中没有任何数据，那么数据库支持的网站的测试用例就没什么用了。测试使用ORM创建对象更易读，也更易维护，例如在 <a class="reference internal" href="#django.test.TestCase.setUpTestData" title="django.test.TestCase.setUpTestData"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TestCase.setUpTestData()</span></code></a> 中。但是，你也可以使用辅助工具。</p>
<p>辅助工具是 Django 知道如何导入数据库的数据集合。例如，如果你的网站有用户账户，你可能会设置一个假用户账户的辅助工具，以便在测试时填充你的数据库。</p>
<p>创建辅助工具的最直接方法是使用 <a class="reference internal" href="../../ref/django-admin.html#django-admin-dumpdata"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">manage.py</span> <span class="pre">dumpdata</span></code></a> 命令。这假定你已经在你的数据库中拥有一些数据。参见 <a class="reference internal" href="../../ref/django-admin.html#django-admin-dumpdata"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">dumpdata</span> <span class="pre">文档</span></code></a> 了解更多细节。</p>
<p>一旦你创建了一个辅助工具，并把它放在你的 <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 中的 <code class="docutils literal notranslate"><span class="pre">fixtures</span></code> 目录下，你就可以通过在你的 <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.test.TestCase</span></code></a> 子类上指定一个 <code class="docutils literal notranslate"><span class="pre">fixtures</span></code> 类属性来在你的单元测试中使用它。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span>
<span class="kn">from</span> <span class="nn">myapp.models</span> <span class="kn">import</span> <span class="n">Animal</span>

<span class="k">class</span> <span class="nc">AnimalTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="n">fixtures</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;mammals.json&#39;</span><span class="p">,</span> <span class="s1">&#39;birds&#39;</span><span class="p">]</span>

    <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Test definitions as before.</span>
        <span class="n">call_setup_methods</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">test_fluffy_animals</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># A test that uses the fixtures.</span>
        <span class="n">call_some_test_code</span><span class="p">()</span>
</pre></div>
</div>
<p>具体来说，将发生以下情况：</p>
<ul class="simple">
<li>在每次测试开始时，在 <code class="docutils literal notranslate"><span class="pre">setUp()</span></code> 运行之前，Django 会对数据库进行刷新，将数据库直接返回到 <a class="reference internal" href="../../ref/django-admin.html#django-admin-migrate"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">migrate</span></code></a> 被调用后的状态。</li>
<li>然后，所有命名的辅助工具都会被安装。在这个例子中，Django 将安装任何名为 <code class="docutils literal notranslate"><span class="pre">mammals</span></code> 的 JSON 辅助工具，然后是任何名为 <code class="docutils literal notranslate"><span class="pre">birds</span></code> 的辅助工具。请参阅 <a class="reference internal" href="../../ref/django-admin.html#django-admin-loaddata"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">loaddata</span></code></a> 文档，了解更多关于定义和安装辅助工具的细节。</li>
</ul>
<p>出于性能方面的考虑， <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> 在 <a class="reference internal" href="#django.test.TestCase.setUpTestData" title="django.test.TestCase.setUpTestData"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setUpTestData()</span></code></a> 之前为整个测试类加载一次辅助工具，而不是在每次测试之前加载，并且它在每次测试之前使用事务来清理数据库。在任何情况下，你都可以确定一个测试的结果不会受到另一个测试或测试执行顺序的影响。</p>
<p>默认情况下，辅助工具只被加载到 <code class="docutils literal notranslate"><span class="pre">default</span></code> 数据库中。如果你使用多个数据库并且设置了 <a class="reference internal" href="#django.test.TransactionTestCase.databases" title="django.test.TransactionTestCase.databases"><code class="xref py py-attr docutils literal notranslate"><span class="pre">TransactionTestCase.databases</span></code></a>，辅助工具将被加载到所有指定的数据库中。</p>
</div>
<div class="section" id="s-urlconf-configuration">
<span id="urlconf-configuration"></span><h3>URLconf 配置<a class="headerlink" href="#urlconf-configuration" title="永久链接至标题">¶</a></h3>
<p>如果你的应用程序提供了视图，你可能希望包含使用测试客户端来行使这些视图的测试。然而，最终用户可以自由地在他们选择的任何 URL 上部署应用程序中的视图。这意味着你的测试不能依赖于你的视图将在特定的 URL 上可用这一事实。用 <code class="docutils literal notranslate"><span class="pre">&#64;override_settings(ROOT_URLCONF=...)</span></code> 来装饰你的测试类或测试方法的 URLconf 配置。</p>
</div>
<div class="section" id="s-multi-database-support">
<span id="s-testing-multi-db"></span><span id="multi-database-support"></span><span id="testing-multi-db"></span><h3>多数据库支持<a class="headerlink" href="#multi-database-support" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.test.TransactionTestCase.databases">
<code class="descclassname">TransactionTestCase.</code><code class="descname">databases</code><a class="headerlink" href="#django.test.TransactionTestCase.databases" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>Django 设置了一个测试数据库，对应于你设置中的 <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATABASES</span></code></a> 定义的并且至少有一个测试引用了 <code class="docutils literal notranslate"><span class="pre">databases</span></code> 的每个数据库。</p>
<p>然而，运行一个 Django <code class="docutils literal notranslate"><span class="pre">TestCase</span></code> 所花费的时间很大一部分是被调用 <code class="docutils literal notranslate"><span class="pre">flush</span></code> 所消耗的，它确保了你在每次测试运行开始时有一个干净的数据库。如果你有多个数据库，就需要多次刷新（每个数据库一个），这可能是一个耗时的活动——特别是当你的测试不需要测试多数据库活动时。</p>
<p>作为一种优化，Django 只在每次测试运行开始时刷新 <code class="docutils literal notranslate"><span class="pre">default</span></code> 数据库。如果你的设置包含多个数据库，并且你的测试要求每个数据库都是干净的，你可以使用测试套件上的 <code class="docutils literal notranslate"><span class="pre">databases</span></code> 属性来请求额外的数据库被刷新。</p>
<p>例如:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">TestMyViews</span><span class="p">(</span><span class="n">TransactionTestCase</span><span class="p">):</span>
    <span class="n">databases</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;default&#39;</span><span class="p">,</span> <span class="s1">&#39;other&#39;</span><span class="p">}</span>

    <span class="k">def</span> <span class="nf">test_index_page_view</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">call_some_test_code</span><span class="p">()</span>
</pre></div>
</div>
<p>这个测试用例将在运行 <code class="docutils literal notranslate"><span class="pre">test_index_page_view</span></code> 之前刷新 <code class="docutils literal notranslate"><span class="pre">default</span></code> 和 <code class="docutils literal notranslate"><span class="pre">other</span></code> 测试数据库。你也可以使用 <code class="docutils literal notranslate"><span class="pre">'__all__'</span></code> 来指定所有的测试数据库必须被刷新。</p>
<p><code class="docutils literal notranslate"><span class="pre">databases</span></code> 标志也控制 <a class="reference internal" href="#django.test.TransactionTestCase.fixtures" title="django.test.TransactionTestCase.fixtures"><code class="xref py py-attr docutils literal notranslate"><span class="pre">TransactionTestCase.fixtures</span></code></a> 被加载到哪些数据库。默认情况下，辅助工具只被加载到 <code class="docutils literal notranslate"><span class="pre">default</span></code> 数据库中。</p>
<p>对不在 <code class="docutils literal notranslate"><span class="pre">databases</span></code> 中的数据库的查询将给出断言错误，以防止测试之间的状态泄露。</p>
<dl class="attribute">
<dt id="django.test.TestCase.databases">
<code class="descclassname">TestCase.</code><code class="descname">databases</code><a class="headerlink" href="#django.test.TestCase.databases" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>默认情况下，在 <code class="docutils literal notranslate"><span class="pre">TestCase</span></code> 期间，仅将 <code class="docutils literal notranslate"><span class="pre">default</span></code> 数据库包装在事务中，并且尝试查询其他数据库将导致断言错误，以防止测试之间的状态泄漏。</p>
<p>在测试类上使用 <code class="docutils literal notranslate"><span class="pre">databases</span></code> 类属性来请求对非 <code class="docutils literal notranslate"><span class="pre">default</span></code> 数据库进行事务包装。</p>
<p>例如:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">OtherDBTests</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="n">databases</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;other&#39;</span><span class="p">}</span>

    <span class="k">def</span> <span class="nf">test_other_db_query</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>这个测试只允许对 <code class="docutils literal notranslate"><span class="pre">other</span></code> 数据库进行查询。就像 <a class="reference internal" href="#django.test.SimpleTestCase.databases" title="django.test.SimpleTestCase.databases"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SimpleTestCase.databases</span></code></a> 和 <a class="reference internal" href="#django.test.TransactionTestCase.databases" title="django.test.TransactionTestCase.databases"><code class="xref py py-attr docutils literal notranslate"><span class="pre">TransactionTestCase.databases</span></code></a> 一样，<code class="docutils literal notranslate"><span class="pre">'__all__'</span></code> 常量可以用来指定测试应该允许对所有数据库进行查询。</p>
</div>
<div class="section" id="s-overriding-settings">
<span id="s-id1"></span><span id="overriding-settings"></span><span id="id1"></span><h3>覆盖配置<a class="headerlink" href="#overriding-settings" title="永久链接至标题">¶</a></h3>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p class="last">使用下面的函数可以临时改变测试中的设置值。不要直接操作 <code class="docutils literal notranslate"><span class="pre">django.conf.settings</span></code>，因为 Django 不会在这种操作后恢复原始值。</p>
</div>
<dl class="method">
<dt id="django.test.SimpleTestCase.settings">
<code class="descclassname">SimpleTestCase.</code><code class="descname">settings</code>()<a class="headerlink" href="#django.test.SimpleTestCase.settings" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>为了测试的目的，经常需要临时改变一个设置，并在运行测试代码后恢复到原始值。对于这个用例，Django 提供了一个标准的 Python 上下文管理器（见 <span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a>），叫做 <a class="reference internal" href="#django.test.SimpleTestCase.settings" title="django.test.SimpleTestCase.settings"><code class="xref py py-meth docutils literal notranslate"><span class="pre">settings()</span></code></a>，可以这样使用：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span>

<span class="k">class</span> <span class="nc">LoginTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">test_login</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>

        <span class="c1"># First check for the default behavior</span>
        <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/sekrit/&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertRedirects</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="s1">&#39;/accounts/login/?next=/sekrit/&#39;</span><span class="p">)</span>

        <span class="c1"># Then override the LOGIN_URL setting</span>
        <span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">settings</span><span class="p">(</span><span class="n">LOGIN_URL</span><span class="o">=</span><span class="s1">&#39;/other/login/&#39;</span><span class="p">):</span>
            <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/sekrit/&#39;</span><span class="p">)</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">assertRedirects</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="s1">&#39;/other/login/?next=/sekrit/&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>本例将覆盖 <code class="docutils literal notranslate"><span class="pre">with</span></code> 块中代码的 <a class="reference internal" href="../../ref/settings.html#std:setting-LOGIN_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">LOGIN_URL</span></code></a> 设置，并在之后将其值重置为之前的状态。</p>
<dl class="method">
<dt id="django.test.SimpleTestCase.modify_settings">
<code class="descclassname">SimpleTestCase.</code><code class="descname">modify_settings</code>()<a class="headerlink" href="#django.test.SimpleTestCase.modify_settings" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>重新定义包含一系列值的设置可能会很麻烦。在实践中，添加或删除值通常是足够的。Django 提供了 <a class="reference internal" href="#django.test.SimpleTestCase.modify_settings" title="django.test.SimpleTestCase.modify_settings"><code class="xref py py-meth docutils literal notranslate"><span class="pre">modify_settings()</span></code></a> 上下文管理器，以方便更改设置：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span>

<span class="k">class</span> <span class="nc">MiddlewareTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">test_cache_middleware</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">modify_settings</span><span class="p">(</span><span class="n">MIDDLEWARE</span><span class="o">=</span><span class="p">{</span>
            <span class="s1">&#39;append&#39;</span><span class="p">:</span> <span class="s1">&#39;django.middleware.cache.FetchFromCacheMiddleware&#39;</span><span class="p">,</span>
            <span class="s1">&#39;prepend&#39;</span><span class="p">:</span> <span class="s1">&#39;django.middleware.cache.UpdateCacheMiddleware&#39;</span><span class="p">,</span>
            <span class="s1">&#39;remove&#39;</span><span class="p">:</span> <span class="p">[</span>
                <span class="s1">&#39;django.contrib.sessions.middleware.SessionMiddleware&#39;</span><span class="p">,</span>
                <span class="s1">&#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;</span><span class="p">,</span>
                <span class="s1">&#39;django.contrib.messages.middleware.MessageMiddleware&#39;</span><span class="p">,</span>
            <span class="p">],</span>
        <span class="p">}):</span>
            <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/&#39;</span><span class="p">)</span>
            <span class="c1"># ...</span>
</pre></div>
</div>
<p>对于每个操作，你可以提供一个值的列表或一个字符串。当值已经存在于列表中时，<code class="docutils literal notranslate"><span class="pre">append</span></code> 和 <code class="docutils literal notranslate"><span class="pre">prepend</span></code> 没有效果；当值不存在时，<code class="docutils literal notranslate"><span class="pre">remove</span></code> 也没有效果。</p>
<dl class="function">
<dt id="django.test.override_settings">
<code class="descname">override_settings</code>()<a class="headerlink" href="#django.test.override_settings" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>如果你想覆盖一个测试方法的设置，Django 提供了 <a class="reference internal" href="#django.test.override_settings" title="django.test.override_settings"><code class="xref py py-func docutils literal notranslate"><span class="pre">override_settings()</span></code></a> 装饰器（见 <span class="target" id="index-8"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0318"><strong>PEP 318</strong></a>）。它的用法是这样的：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span><span class="p">,</span> <span class="n">override_settings</span>

<span class="k">class</span> <span class="nc">LoginTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="nd">@override_settings</span><span class="p">(</span><span class="n">LOGIN_URL</span><span class="o">=</span><span class="s1">&#39;/other/login/&#39;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test_login</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/sekrit/&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertRedirects</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="s1">&#39;/other/login/?next=/sekrit/&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>装饰器也可以应用于 <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> 类：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span><span class="p">,</span> <span class="n">override_settings</span>

<span class="nd">@override_settings</span><span class="p">(</span><span class="n">LOGIN_URL</span><span class="o">=</span><span class="s1">&#39;/other/login/&#39;</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">LoginTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">test_login</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/sekrit/&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertRedirects</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="s1">&#39;/other/login/?next=/sekrit/&#39;</span><span class="p">)</span>
</pre></div>
</div>
<dl class="function">
<dt id="django.test.modify_settings">
<code class="descname">modify_settings</code>()<a class="headerlink" href="#django.test.modify_settings" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>同样，Django 也提供了 <a class="reference internal" href="#django.test.modify_settings" title="django.test.modify_settings"><code class="xref py py-func docutils literal notranslate"><span class="pre">modify_settings()</span></code></a> 装饰器：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span><span class="p">,</span> <span class="n">modify_settings</span>

<span class="k">class</span> <span class="nc">MiddlewareTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="nd">@modify_settings</span><span class="p">(</span><span class="n">MIDDLEWARE</span><span class="o">=</span><span class="p">{</span>
        <span class="s1">&#39;append&#39;</span><span class="p">:</span> <span class="s1">&#39;django.middleware.cache.FetchFromCacheMiddleware&#39;</span><span class="p">,</span>
        <span class="s1">&#39;prepend&#39;</span><span class="p">:</span> <span class="s1">&#39;django.middleware.cache.UpdateCacheMiddleware&#39;</span><span class="p">,</span>
    <span class="p">})</span>
    <span class="k">def</span> <span class="nf">test_cache_middleware</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/&#39;</span><span class="p">)</span>
        <span class="c1"># ...</span>
</pre></div>
</div>
<p>此装饰器也可以应用于测试用例类：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span><span class="p">,</span> <span class="n">modify_settings</span>

<span class="nd">@modify_settings</span><span class="p">(</span><span class="n">MIDDLEWARE</span><span class="o">=</span><span class="p">{</span>
    <span class="s1">&#39;append&#39;</span><span class="p">:</span> <span class="s1">&#39;django.middleware.cache.FetchFromCacheMiddleware&#39;</span><span class="p">,</span>
    <span class="s1">&#39;prepend&#39;</span><span class="p">:</span> <span class="s1">&#39;django.middleware.cache.UpdateCacheMiddleware&#39;</span><span class="p">,</span>
<span class="p">})</span>
<span class="k">class</span> <span class="nc">MiddlewareTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">test_cache_middleware</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/&#39;</span><span class="p">)</span>
        <span class="c1"># ...</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">当给定一个类时，这些装饰器直接修改该类并返回它，它们不会创建并返回一个修改后的副本。因此，如果你试图调整上面的例子，将返回值分配给一个不同于 <code class="docutils literal notranslate"><span class="pre">LoginTestCase</span></code> 或 <code class="docutils literal notranslate"><span class="pre">MiddlewareTestCase</span></code> 的名称，你可能会惊讶地发现，原来的测试用例类仍然同样受到装饰器的影响。对于一个给定的类，<a class="reference internal" href="#django.test.modify_settings" title="django.test.modify_settings"><code class="xref py py-func docutils literal notranslate"><span class="pre">modify_settings()</span></code></a> 总是应用在 <a class="reference internal" href="#django.test.override_settings" title="django.test.override_settings"><code class="xref py py-func docutils literal notranslate"><span class="pre">override_settings()</span></code></a> 之后。</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p>配置文件中包含了一些设置，这些设置只有在 Django 内部初始化时才会被使用。如果你用 <code class="docutils literal notranslate"><span class="pre">override_settings</span></code> 改变它们，当你通过``django.conf.settings`` 模块访问会得到被改变的配置。但是，Django 的内部程序访问它的方式是不同的。实际上，使用 <a class="reference internal" href="#django.test.override_settings" title="django.test.override_settings"><code class="xref py py-func docutils literal notranslate"><span class="pre">override_settings()</span></code></a> 或者 <a class="reference internal" href="#django.test.modify_settings" title="django.test.modify_settings"><code class="xref py py-func docutils literal notranslate"><span class="pre">modify_settings()</span></code></a> 来使用这些设置，很可能达不到你预期的效果。</p>
<p>我们不建议改变 <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATABASES</span></code></a> 的设置。改变 <a class="reference internal" href="../../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHES</span></code></a> 的设置是可能的，但如果你使用的是内部缓存，比如 <code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.session</span></code>，就有点棘手。例如，你必须在使用缓存会话并覆盖 <a class="reference internal" href="../../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHES</span></code></a> 的测试中重新初始化会话后端。</p>
<p class="last">最后，避免将你的配置别名为模块级常量，因为 <code class="docutils literal notranslate"><span class="pre">override_settings()</span></code> 不会对这些值起作用，它们只在第一次导入模块时才被评估。</p>
</div>
<p>你也可以在配置被覆盖后，通过删除配置来模拟没有配置，比如这样：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@override_settings</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">test_something</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="k">del</span> <span class="n">settings</span><span class="o">.</span><span class="n">LOGIN_URL</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>覆盖配置时，请确保处理你的应用代码使用即使保留配置更改也能保持状态的缓存或类似功能的情况。Django 提供了 <a class="reference internal" href="../../ref/signals.html#django.test.signals.setting_changed" title="django.test.signals.setting_changed"><code class="xref py py-data docutils literal notranslate"><span class="pre">django.test.signals.setting_changed</span></code></a> 信号，让你在设置被改变时，可以注册回调来清理和重置状态。</p>
<p>Django 自己也使用这个信号来重置各种数据。</p>
<table class="docutils">
<colgroup>
<col width="43%" />
<col width="57%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">覆盖配置</th>
<th class="head">数据重置</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>USE_TZ，TIME_ZONE</td>
<td>数据库时区</td>
</tr>
<tr class="row-odd"><td>TEMPLATES</td>
<td>模板引擎</td>
</tr>
<tr class="row-even"><td>SERIALIZATION_MODULES</td>
<td>序列化器缓存</td>
</tr>
<tr class="row-odd"><td>LOCALE_PATHS，LANGUAGE_CODE</td>
<td>默认翻译和加载的翻译</td>
</tr>
<tr class="row-even"><td>MEDIA_ROOT，DEFAULT_FILE_STORAGE</td>
<td>默认文件存储</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="s-emptying-the-test-outbox">
<span id="s-emptying-test-outbox"></span><span id="emptying-the-test-outbox"></span><span id="emptying-test-outbox"></span><h3>清空测试发件箱<a class="headerlink" href="#emptying-the-test-outbox" title="永久链接至标题">¶</a></h3>
<p>如果你使用任何 Django 的自定义 <code class="docutils literal notranslate"><span class="pre">TestCase</span></code> 类，测试运行器将在每个测试用例开始时清除测试邮件发件箱的内容。</p>
<p>关于测试期间电子邮件服务的更多细节，请参见下面的 <a class="reference internal" href="#email-services">Email services</a>。</p>
</div>
<div class="section" id="s-assertions">
<span id="s-id2"></span><span id="assertions"></span><span id="id2"></span><h3>断言<a class="headerlink" href="#assertions" title="永久链接至标题">¶</a></h3>
<p>由于 Python 的普通 <a class="reference external" href="https://docs.python.org/3/library/unittest.html#unittest.TestCase" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestCase</span></code></a> 类实现了 <a class="reference external" href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertTrue" title="(在 Python v3.10)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertTrue()</span></code></a> 和 <a class="reference external" href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertEqual" title="(在 Python v3.10)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a> 等断言方法，Django 的自定义 <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> 类提供了许多自定义的断言方法，这些方法对于测试 Web 应用非常有用。</p>
<p>大多数这些断言方法给出的失败信息可以用 <code class="docutils literal notranslate"><span class="pre">msg_prefix</span></code> 参数自定义。这个字符串将被加在断言产生的任何失败信息的前面。这允许你提供额外的细节，以帮助你确定测试套件中失败的位置和原因。</p>
<dl class="method">
<dt id="django.test.SimpleTestCase.assertRaisesMessage">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertRaisesMessage</code>(<em>expected_exception</em>, <em>expected_message</em>, <em>callable</em>, <em>*args</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertRaisesMessage" title="永久链接至目标">¶</a></dt>
<dt>
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertRaisesMessage</code>(<em>expected_exception</em>, <em>expected_message</em>)</dt>
<dd><p>断言执行 <code class="docutils literal notranslate"><span class="pre">callable</span></code> 引起 <code class="docutils literal notranslate"><span class="pre">expected_exception</span></code>，并且在异常信息中发现 <code class="docutils literal notranslate"><span class="pre">expected_message</span></code>。任何其他结果都会被报告为失败。它是 <a class="reference external" href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaisesRegex" title="(在 Python v3.10)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unittest.TestCase.assertRaisesRegex()</span></code></a> 的简单版本，不同的是 <code class="docutils literal notranslate"><span class="pre">expected_message</span></code> 不作为正则表达式处理。</p>
<p>如果只给了 <code class="docutils literal notranslate"><span class="pre">expected_exception</span></code> 和 <code class="docutils literal notranslate"><span class="pre">expected_message</span></code> 参数，则返回一个上下文管理器，以便被测试的代码可以内联而不是作为一个函数来写：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRaisesMessage</span><span class="p">(</span><span class="ne">ValueError</span><span class="p">,</span> <span class="s1">&#39;invalid literal for int()&#39;</span><span class="p">):</span>
    <span class="nb">int</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertWarnsMessage">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertWarnsMessage</code>(<em>expected_warning</em>, <em>expected_message</em>, <em>callable</em>, <em>*args</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertWarnsMessage" title="永久链接至目标">¶</a></dt>
<dt>
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertWarnsMessage</code>(<em>expected_warning</em>, <em>expected_message</em>)</dt>
<dd><p>类似于 <a class="reference internal" href="#django.test.SimpleTestCase.assertRaisesMessage" title="django.test.SimpleTestCase.assertRaisesMessage"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SimpleTestCase.assertRaisesMessage()</span></code></a>，但是 <a class="reference external" href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertWarnsRegex" title="(在 Python v3.10)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertWarnsRegex()</span></code></a> 代替 <a class="reference external" href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaisesRegex" title="(在 Python v3.10)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRaisesRegex()</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertFieldOutput">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertFieldOutput</code>(<em>fieldclass</em>, <em>valid</em>, <em>invalid</em>, <em>field_args=None</em>, <em>field_kwargs=None</em>, <em>empty_value=''</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertFieldOutput" title="永久链接至目标">¶</a></dt>
<dd><p>断言表单字段在不同的输入情况下表现正确。</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple">
<li><strong>fieldclass</strong> -- 待测试字段的类。</li>
<li><strong>valid</strong> -- 一个字典，将有效输入映射到它们的预期干净值。</li>
<li><strong>invalid</strong> -- 一个字典，将无效输入映射到一个或多个引发的错误信息</li>
<li><strong>field_args</strong> -- 传递给实例化字段的 args。</li>
<li><strong>field_kwargs</strong> -- 传递给实例化字段的 kwargs。</li>
<li><strong>empty_value</strong> -- <code class="docutils literal notranslate"><span class="pre">empty_values</span></code> 中输入的预期干净输出。</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>例如，以下代码测试 <code class="docutils literal notranslate"><span class="pre">EmailField</span></code> 接受 <code class="docutils literal notranslate"><span class="pre">a&#64;a.com</span></code> 作为有效的电子邮件地址，但拒绝 <code class="docutils literal notranslate"><span class="pre">aaa</span></code>，并给出合理的错误信息：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="bp">self</span><span class="o">.</span><span class="n">assertFieldOutput</span><span class="p">(</span><span class="n">EmailField</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;a@a.com&#39;</span><span class="p">:</span> <span class="s1">&#39;a@a.com&#39;</span><span class="p">},</span> <span class="p">{</span><span class="s1">&#39;aaa&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;Enter a valid email address.&#39;</span><span class="p">]})</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertFormError">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertFormError</code>(<em>response</em>, <em>form</em>, <em>field</em>, <em>errors</em>, <em>msg_prefix=''</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertFormError" title="永久链接至目标">¶</a></dt>
<dd><p>断言表单中的某个字段在表单中呈现时，会引发所提供的错误列表。</p>
<p><code class="docutils literal notranslate"><span class="pre">form</span></code> 是 <code class="docutils literal notranslate"><span class="pre">Form</span></code> 实例在模板上下文中被赋予的名称。</p>
<p><code class="docutils literal notranslate"><span class="pre">field</span></code> 是表单中要检查的字段名。如果 <code class="docutils literal notranslate"><span class="pre">field</span></code> 的值为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则会检查非字段错误（可以通过 <a class="reference internal" href="../../ref/forms/api.html#django.forms.Form.non_field_errors" title="django.forms.Form.non_field_errors"><code class="xref py py-meth docutils literal notranslate"><span class="pre">form.non_field_errors()</span></code></a>）。</p>
<p><code class="docutils literal notranslate"><span class="pre">errors</span></code> 是一个错误字符串，或一个错误字符串列表，是表单验证的结果。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertFormsetError">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertFormsetError</code>(<em>response</em>, <em>formset</em>, <em>form_index</em>, <em>field</em>, <em>errors</em>, <em>msg_prefix=''</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertFormsetError" title="永久链接至目标">¶</a></dt>
<dd><p>断言 <code class="docutils literal notranslate"><span class="pre">formset</span></code> 在渲染时，会引发所提供的错误列表。</p>
<p><code class="docutils literal notranslate"><span class="pre">formset</span></code> 是 <code class="docutils literal notranslate"><span class="pre">Formset</span></code> 实例在模板上下文中被赋予的名称。</p>
<p><code class="docutils literal notranslate"><span class="pre">form_index</span></code> 是 <code class="docutils literal notranslate"><span class="pre">Formset</span></code> 中表单的编号。 如果 <code class="docutils literal notranslate"><span class="pre">form_index</span></code> 的值为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则将检查非表单错误（可以通过 <code class="docutils literal notranslate"><span class="pre">formset.non_form_errors()</span></code> 访问的错误）。</p>
<p><code class="docutils literal notranslate"><span class="pre">field</span></code> 是表单中要检查的字段名。如果 <code class="docutils literal notranslate"><span class="pre">field</span></code> 的值为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则会检查非字段错误（可以通过 <a class="reference internal" href="../../ref/forms/api.html#django.forms.Form.non_field_errors" title="django.forms.Form.non_field_errors"><code class="xref py py-meth docutils literal notranslate"><span class="pre">form.non_field_errors()</span></code></a>）。</p>
<p><code class="docutils literal notranslate"><span class="pre">errors</span></code> 是一个错误字符串，或一个错误字符串列表，是表单验证的结果。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertContains">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertContains</code>(<em>response</em>, <em>text</em>, <em>count=None</em>, <em>status_code=200</em>, <em>msg_prefix=''</em>, <em>html=False</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertContains" title="永久链接至目标">¶</a></dt>
<dd><p>断言一个 <code class="docutils literal notranslate"><span class="pre">Response</span></code> 实例产生了给定的 <code class="docutils literal notranslate"><span class="pre">status_code</span></code>，并且 <code class="docutils literal notranslate"><span class="pre">text</span></code> 出现在响应的内容中。如果提供了 <code class="docutils literal notranslate"><span class="pre">count</span></code>，则 <code class="docutils literal notranslate"><span class="pre">text</span></code> 必须在响应中准确出现 <code class="docutils literal notranslate"><span class="pre">count</span></code> 次。</p>
<p>将 <code class="docutils literal notranslate"><span class="pre">html</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，将 <code class="docutils literal notranslate"><span class="pre">text</span></code> 作为 HTML 处理。与响应内容的比较将基于 HTML 语义，而不是逐个字符的平等。在大多数情况下，空格会被忽略，属性排序并不重要。详见 <a class="reference internal" href="#django.test.SimpleTestCase.assertHTMLEqual" title="django.test.SimpleTestCase.assertHTMLEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertHTMLEqual()</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertNotContains">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertNotContains</code>(<em>response</em>, <em>text</em>, <em>status_code=200</em>, <em>msg_prefix=''</em>, <em>html=False</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertNotContains" title="永久链接至目标">¶</a></dt>
<dd><p>断言一个 <code class="docutils literal notranslate"><span class="pre">Response</span></code> 实例产生了给定的 <code class="docutils literal notranslate"><span class="pre">status_code</span></code>，而且 <code class="docutils literal notranslate"><span class="pre">text</span></code> <em>没有</em> 出现在响应的内容中。</p>
<p>将 <code class="docutils literal notranslate"><span class="pre">html</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，将 <code class="docutils literal notranslate"><span class="pre">text</span></code> 作为 HTML 处理。与响应内容的比较将基于 HTML 语义，而不是逐个字符的平等。在大多数情况下，空格会被忽略，属性排序并不重要。详见 <a class="reference internal" href="#django.test.SimpleTestCase.assertHTMLEqual" title="django.test.SimpleTestCase.assertHTMLEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertHTMLEqual()</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertTemplateUsed">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertTemplateUsed</code>(<em>response</em>, <em>template_name</em>, <em>msg_prefix=''</em>, <em>count=None</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertTemplateUsed" title="永久链接至目标">¶</a></dt>
<dd><p>断言给定名称的模板被用于渲染响应。</p>
<p>名称是一个字符串，如 <code class="docutils literal notranslate"><span class="pre">'admin/index.html'</span></code>。</p>
<p>参数 counter 是一个整数，表示模板应该被渲染的次数。默认值是 <code class="docutils literal notranslate"><span class="pre">None</span></code>，即模板应被渲染一次或多次。</p>
<p>你可以把它作为一个上下文管理器，比如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertTemplateUsed</span><span class="p">(</span><span class="s1">&#39;index.html&#39;</span><span class="p">):</span>
    <span class="n">render_to_string</span><span class="p">(</span><span class="s1">&#39;index.html&#39;</span><span class="p">)</span>
<span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertTemplateUsed</span><span class="p">(</span><span class="n">template_name</span><span class="o">=</span><span class="s1">&#39;index.html&#39;</span><span class="p">):</span>
    <span class="n">render_to_string</span><span class="p">(</span><span class="s1">&#39;index.html&#39;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertTemplateNotUsed">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertTemplateNotUsed</code>(<em>response</em>, <em>template_name</em>, <em>msg_prefix=''</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertTemplateNotUsed" title="永久链接至目标">¶</a></dt>
<dd><p>断言给定名称的模板在渲染响应时 <em>没有</em> 被使用。</p>
<p>你可以用 <a class="reference internal" href="#django.test.SimpleTestCase.assertTemplateUsed" title="django.test.SimpleTestCase.assertTemplateUsed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertTemplateUsed()</span></code></a> 一样的方式将其作为上下文管理器。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertURLEqual">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertURLEqual</code>(<em>url1</em>, <em>url2</em>, <em>msg_prefix=''</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertURLEqual" title="永久链接至目标">¶</a></dt>
<dd><p>断言两个 URL 是相同的，忽略查询字符串参数的顺序，但同名参数除外。例如，<code class="docutils literal notranslate"><span class="pre">/path/?x=1&amp;y=2</span></code> 等于 <code class="docutils literal notranslate"><span class="pre">/path/?y=2&amp;x=1</span></code>，但 <code class="docutils literal notranslate"><span class="pre">/path/?a=1&amp;a=2</span></code> 不等于 <code class="docutils literal notranslate"><span class="pre">/path/?a=2&amp;a=1</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertRedirects">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertRedirects</code>(<em>response</em>, <em>expected_url</em>, <em>status_code=302</em>, <em>target_status_code=200</em>, <em>msg_prefix=''</em>, <em>fetch_redirect_response=True</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertRedirects" title="永久链接至目标">¶</a></dt>
<dd><p>断言响应返回了 <code class="docutils literal notranslate"><span class="pre">status_code</span></code> 重定向状态，重定向到 <code class="docutils literal notranslate"><span class="pre">expected_url</span></code> （包括任何 <code class="docutils literal notranslate"><span class="pre">GET</span></code> 数据），最后页面收到的是 <code class="docutils literal notranslate"><span class="pre">target_status_code</span></code>。</p>
<p>如果你的请求使用了 <code class="docutils literal notranslate"><span class="pre">follow</span></code> 参数，<code class="docutils literal notranslate"><span class="pre">expected_url</span></code> 和 <code class="docutils literal notranslate"><span class="pre">target_status_code</span></code> 将是重定向链最后一点的网址和状态码。</p>
<p>如果 <code class="docutils literal notranslate"><span class="pre">fetch_redirect_response</span></code> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code>，则最终页面不会被加载。由于测试客户端不能获取外部 URL，所以如果 <code class="docutils literal notranslate"><span class="pre">expected_url</span></code> 不是 Django 应用的一部分，这一点就特别有用。</p>
<p>在两个 URL 之间进行比较时，可以正确处理协议。如果在我们被重定向到的位置没有指定任何协议，则使用原始请求的协议。如果存在，<code class="docutils literal notranslate"><span class="pre">expected_url</span></code> 中的协议就是用来进行比较的。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertHTMLEqual">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertHTMLEqual</code>(<em>html1</em>, <em>html2</em>, <em>msg=None</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertHTMLEqual" title="永久链接至目标">¶</a></dt>
<dd><p>断言字符串 <code class="docutils literal notranslate"><span class="pre">html1</span></code> 和 <code class="docutils literal notranslate"><span class="pre">html2</span></code> 相等。比较是基于 HTML 语义的。比较时考虑到以下因素：</p>
<ul class="simple">
<li>HTML 标签前后的空白会被忽略。</li>
<li>所有类型的空白都被认为是等价的。</li>
<li>所有打开的标签都是隐式关闭的，例如当周围的标签关闭或 HTML 文档结束时。</li>
<li>空标签相当于其自动闭合版。</li>
<li>HTML 元素的属性排序并不重要。</li>
<li>没有参数的属性等于名称和值相等的属性（见示例）。</li>
<li>引用同一字符的文本、字符引用和实体引用是等价的。</li>
</ul>
<p>下面的例子是有效的测试，并且没有引起任何 <code class="docutils literal notranslate"><span class="pre">AssertionError</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="bp">self</span><span class="o">.</span><span class="n">assertHTMLEqual</span><span class="p">(</span>
    <span class="s1">&#39;&lt;p&gt;Hello &lt;b&gt;&amp;#x27;world&amp;#x27;!&lt;/p&gt;&#39;</span><span class="p">,</span>
    <span class="sd">&#39;&#39;&#39;&lt;p&gt;</span>
<span class="sd">        Hello   &lt;b&gt;&amp;#39;world&amp;#39;! &lt;/b&gt;</span>
<span class="sd">    &lt;/p&gt;&#39;&#39;&#39;</span>
<span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertHTMLEqual</span><span class="p">(</span>
    <span class="s1">&#39;&lt;input type=&quot;checkbox&quot; checked=&quot;checked&quot; id=&quot;id_accept_terms&quot; /&gt;&#39;</span><span class="p">,</span>
    <span class="s1">&#39;&lt;input id=&quot;id_accept_terms&quot; type=&quot;checkbox&quot; checked&gt;&#39;</span>
<span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">html1</span></code> 和 <code class="docutils literal notranslate"><span class="pre">html2</span></code> 必须包含 HTML。如果其中一个不能被解析，将产生一个 <code class="docutils literal notranslate"><span class="pre">AssertionError</span></code>。</p>
<p>错误时的输出可以用 <code class="docutils literal notranslate"><span class="pre">msg</span></code> 参数自定义。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertHTMLNotEqual">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertHTMLNotEqual</code>(<em>html1</em>, <em>html2</em>, <em>msg=None</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertHTMLNotEqual" title="永久链接至目标">¶</a></dt>
<dd><p>断言字符串 <code class="docutils literal notranslate"><span class="pre">html1</span></code> 和 <code class="docutils literal notranslate"><span class="pre">html2</span></code> <em>不</em> 相等。比较是基于 HTML 语义的。详见 <a class="reference internal" href="#django.test.SimpleTestCase.assertHTMLEqual" title="django.test.SimpleTestCase.assertHTMLEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertHTMLEqual()</span></code></a>。</p>
<p><code class="docutils literal notranslate"><span class="pre">html1</span></code> 和 <code class="docutils literal notranslate"><span class="pre">html2</span></code> 必须包含 HTML。如果其中一个不能被解析，将产生一个 <code class="docutils literal notranslate"><span class="pre">AssertionError</span></code>。</p>
<p>错误时的输出可以用 <code class="docutils literal notranslate"><span class="pre">msg</span></code> 参数自定义。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertXMLEqual">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertXMLEqual</code>(<em>xml1</em>, <em>xml2</em>, <em>msg=None</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertXMLEqual" title="永久链接至目标">¶</a></dt>
<dd><p>断言字符串 <code class="docutils literal notranslate"><span class="pre">xml1</span></code> 和 <code class="docutils literal notranslate"><span class="pre">xml2</span></code> 相等。比较是基于 XML 语义的。与 <a class="reference internal" href="#django.test.SimpleTestCase.assertHTMLEqual" title="django.test.SimpleTestCase.assertHTMLEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertHTMLEqual()</span></code></a> 类似，比较是在解析内容上进行的，因此只考虑语义差异，而不是语法差异。当任何参数中传递了无效的 XML 时，即使两个字符串相同，也总是会引发一个 <code class="docutils literal notranslate"><span class="pre">AssertionError</span></code>。</p>
<p>忽略 XML 声明、文档类型、处理指令和注释。只有根元素和它的子元素被比较。</p>
<p>错误时的输出可以用 <code class="docutils literal notranslate"><span class="pre">msg</span></code> 参数自定义。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertXMLNotEqual">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertXMLNotEqual</code>(<em>xml1</em>, <em>xml2</em>, <em>msg=None</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertXMLNotEqual" title="永久链接至目标">¶</a></dt>
<dd><p>断言字符串 <code class="docutils literal notranslate"><span class="pre">xml1</span></code> 和 <code class="docutils literal notranslate"><span class="pre">xml2</span></code> <em>不</em> 相等。比较是基于 XML 语义的，参见 <a class="reference internal" href="#django.test.SimpleTestCase.assertXMLEqual" title="django.test.SimpleTestCase.assertXMLEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertXMLEqual()</span></code></a>。</p>
<p>错误时的输出可以用 <code class="docutils literal notranslate"><span class="pre">msg</span></code> 参数自定义。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertInHTML">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertInHTML</code>(<em>needle</em>, <em>haystack</em>, <em>count=None</em>, <em>msg_prefix=''</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertInHTML" title="永久链接至目标">¶</a></dt>
<dd><p>断言 HTML 片段 <code class="docutils literal notranslate"><span class="pre">needle</span></code> 包含在 <code class="docutils literal notranslate"><span class="pre">haystack</span></code> 中。</p>
<p>如果指定了 <code class="docutils literal notranslate"><span class="pre">count</span></code> 整数参数，则将严格核查 <code class="docutils literal notranslate"><span class="pre">needle</span></code> 的出现次数。</p>
<p>在大多数情况下，空白是被忽略的，属性排序并不重要。参见 <a class="reference internal" href="#django.test.SimpleTestCase.assertHTMLEqual" title="django.test.SimpleTestCase.assertHTMLEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertHTMLEqual()</span></code></a> 以了解更多细节。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertJSONEqual">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertJSONEqual</code>(<em>raw</em>, <em>expected_data</em>, <em>msg=None</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertJSONEqual" title="永久链接至目标">¶</a></dt>
<dd><p>断言 JSON 片段 <code class="docutils literal notranslate"><span class="pre">raw</span></code> 和 <code class="docutils literal notranslate"><span class="pre">expected_data</span></code> 相等。通常的 JSON 非显性空格规则适用，因为重量级是委托给 <a class="reference external" href="https://docs.python.org/3/library/json.html#module-json" title="(在 Python v3.10)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> 库的。</p>
<p>错误时的输出可以用 <code class="docutils literal notranslate"><span class="pre">msg</span></code> 参数自定义。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.SimpleTestCase.assertJSONNotEqual">
<code class="descclassname">SimpleTestCase.</code><code class="descname">assertJSONNotEqual</code>(<em>raw</em>, <em>expected_data</em>, <em>msg=None</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertJSONNotEqual" title="永久链接至目标">¶</a></dt>
<dd><p>断言 JSON 片段 <code class="docutils literal notranslate"><span class="pre">raw</span></code> 和 <code class="docutils literal notranslate"><span class="pre">expected_data</span></code> <em>不</em> 相等。详见 <a class="reference internal" href="#django.test.SimpleTestCase.assertJSONEqual" title="django.test.SimpleTestCase.assertJSONEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertJSONEqual()</span></code></a>。</p>
<p>错误时的输出可以用 <code class="docutils literal notranslate"><span class="pre">msg</span></code> 参数自定义。</p>
</dd></dl>

<dl class="method">
<dt id="django.test.TransactionTestCase.assertQuerysetEqual">
<code class="descclassname">TransactionTestCase.</code><code class="descname">assertQuerysetEqual</code>(<em>qs</em>, <em>values</em>, <em>transform=None</em>, <em>ordered=True</em>, <em>msg=None</em>)<a class="headerlink" href="#django.test.TransactionTestCase.assertQuerysetEqual" title="永久链接至目标">¶</a></dt>
<dd><p>断言一个查询集 <code class="docutils literal notranslate"><span class="pre">qs</span></code> 与一个特定的可迭代对象 <code class="docutils literal notranslate"><span class="pre">values</span></code> 的值匹配。</p>
<p>如果提供了 <code class="docutils literal notranslate"><span class="pre">transform</span></code>，<code class="docutils literal notranslate"><span class="pre">values</span></code> 将与应用 <code class="docutils literal notranslate"><span class="pre">transform</span></code> 于 <code class="docutils literal notranslate"><span class="pre">qs</span></code> 而产生的列表中每个成员进行比较。</p>
<p>默认情况下，比较也是依赖于顺序的。如果 <code class="docutils literal notranslate"><span class="pre">qs</span></code> 不提供隐式排序，你可以将 <code class="docutils literal notranslate"><span class="pre">ordered</span></code> 参数设置为 <code class="docutils literal notranslate"><span class="pre">False</span></code>，这将使比较变成 <code class="docutils literal notranslate"><span class="pre">collections.Counter</span></code> 比较。如果顺序是未定义的（如果给定的 <code class="docutils literal notranslate"><span class="pre">qs</span></code> 不是有序的，并且比较的对象是一个以上的有序值），会产生一个 <code class="docutils literal notranslate"><span class="pre">ValueError</span></code>。</p>
<p>错误时的输出可以用 <code class="docutils literal notranslate"><span class="pre">msg</span></code> 参数自定义。</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p><code class="docutils literal notranslate"><span class="pre">transform</span></code> 参数的默认值改为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
</div>
<div class="versionadded">
<span class="title">New in Django 3.2:</span> <p>增加了对查询集之间直接比较的支持。</p>
</div>
<div class="deprecated">
<p><span class="versionmodified">3.2 版后已移除: </span>如果没有提供 <code class="docutils literal notranslate"><span class="pre">transform</span></code>，并且 <code class="docutils literal notranslate"><span class="pre">values</span></code> 是一个字符串列表，它将被比作一个对 <code class="docutils literal notranslate"><span class="pre">qs</span></code> 的每个成员应用 <code class="docutils literal notranslate"><span class="pre">repr()</span></code> 产生的列表。这一行为已被废弃，并将在 Django 4.1 中被移除。如果你需要它，可以明确地将 <code class="docutils literal notranslate"><span class="pre">transform</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">repr</span></code>。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="django.test.TransactionTestCase.assertNumQueries">
<code class="descclassname">TransactionTestCase.</code><code class="descname">assertNumQueries</code>(<em>num</em>, <em>func</em>, <em>*args</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.test.TransactionTestCase.assertNumQueries" title="永久链接至目标">¶</a></dt>
<dd><p>断言当 <code class="docutils literal notranslate"><span class="pre">func</span></code> 与 <code class="docutils literal notranslate"><span class="pre">*args</span></code> 和 <code class="docutils literal notranslate"><span class="pre">**kwargs</span></code> 一起调用时，会执行 <code class="docutils literal notranslate"><span class="pre">num</span></code> 次数据库查询。</p>
<p>如果 <code class="docutils literal notranslate"><span class="pre">kwargs</span></code> 中存在 <code class="docutils literal notranslate"><span class="pre">&quot;using&quot;</span></code> 键，则使用该键作为数据库别名，以检查查询次数：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="bp">self</span><span class="o">.</span><span class="n">assertNumQueries</span><span class="p">(</span><span class="mi">7</span><span class="p">,</span> <span class="n">using</span><span class="o">=</span><span class="s1">&#39;non_default_db&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>如果你想调用一个带有 <code class="docutils literal notranslate"><span class="pre">using</span></code> 参数的函数，你可以通过用 <code class="docutils literal notranslate"><span class="pre">lambda</span></code> 包装调用来增加一个额外的参数：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="bp">self</span><span class="o">.</span><span class="n">assertNumQueries</span><span class="p">(</span><span class="mi">7</span><span class="p">,</span> <span class="k">lambda</span><span class="p">:</span> <span class="n">my_function</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="mi">7</span><span class="p">))</span>
</pre></div>
</div>
<p>你也可以用它作为上下文管理器:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertNumQueries</span><span class="p">(</span><span class="mi">2</span><span class="p">):</span>
    <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;Aaron&quot;</span><span class="p">)</span>
    <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;Daniel&quot;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="s-tagging-tests">
<span id="s-topics-tagging-tests"></span><span id="tagging-tests"></span><span id="topics-tagging-tests"></span><h3>标记测试<a class="headerlink" href="#tagging-tests" title="永久链接至标题">¶</a></h3>
<p>你可以给你的测试打上标签，这样你就可以轻松地运行一个特定的子集。例如，你可以标记快速或慢速测试：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">tag</span>

<span class="k">class</span> <span class="nc">SampleTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="nd">@tag</span><span class="p">(</span><span class="s1">&#39;fast&#39;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test_fast</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>

    <span class="nd">@tag</span><span class="p">(</span><span class="s1">&#39;slow&#39;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test_slow</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>

    <span class="nd">@tag</span><span class="p">(</span><span class="s1">&#39;slow&#39;</span><span class="p">,</span> <span class="s1">&#39;core&#39;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test_slow_but_core</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>你也可以标记一个测试用例：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@tag</span><span class="p">(</span><span class="s1">&#39;slow&#39;</span><span class="p">,</span> <span class="s1">&#39;core&#39;</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">SampleTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>子类从超类继承标签，方法从其类继承标签。如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@tag</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">SampleTestCaseChild</span><span class="p">(</span><span class="n">SampleTestCase</span><span class="p">):</span>

    <span class="nd">@tag</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">SampleTestCaseChild.test</span></code> 将用 <code class="docutils literal notranslate"><span class="pre">'slow'</span></code>、<code class="docutils literal notranslate"><span class="pre">'core'</span></code>、<code class="docutils literal notranslate"><span class="pre">'bar'</span></code> 和 <code class="docutils literal notranslate"><span class="pre">'foo'</span></code> 来标注。</p>
<p>然后你可以选择要运行的测试。例如，只运行快速测试：</p>
<div class="console-block" id="console-block-2">
<input class="c-tab-unix" id="c-tab-2-unix" type="radio" name="console-2" checked>
<label for="c-tab-2-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-2-win" type="radio" name="console-2">
<label for="c-tab-2-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-2-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./manage.py <span class="nb">test</span> --tag<span class="o">=</span>fast
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-2-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> manage.py test --tag=fast
</pre></div>
</section>
</div>
<p>或者运行快速测试和核心测试（即使它很慢）：</p>
<div class="console-block" id="console-block-3">
<input class="c-tab-unix" id="c-tab-3-unix" type="radio" name="console-3" checked>
<label for="c-tab-3-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-3-win" type="radio" name="console-3">
<label for="c-tab-3-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-3-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./manage.py <span class="nb">test</span> --tag<span class="o">=</span>fast --tag<span class="o">=</span>core
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-3-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> manage.py test --tag=fast --tag=core
</pre></div>
</section>
</div>
<p>你也可以通过标签来排除测试。如果要运行不慢的核心测试：</p>
<div class="console-block" id="console-block-4">
<input class="c-tab-unix" id="c-tab-4-unix" type="radio" name="console-4" checked>
<label for="c-tab-4-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-4-win" type="radio" name="console-4">
<label for="c-tab-4-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-4-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./manage.py <span class="nb">test</span> --tag<span class="o">=</span>core --exclude-tag<span class="o">=</span>slow
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-4-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> manage.py test --tag=core --exclude-tag=slow
</pre></div>
</section>
</div>
<p><code class="xref std std-option docutils literal notranslate"><span class="pre">test</span> <span class="pre">--exclud-tag</span></code> 优先于 <a class="reference internal" href="../../ref/django-admin.html#cmdoption-test-tag"><code class="xref std std-option docutils literal notranslate"><span class="pre">test</span> <span class="pre">--tag</span></code></a>，所以如果一个测试有两个标签，你选择了其中一个而排除了另一个，测试就不会被运行。</p>
</div>
</div>
<div class="section" id="s-testing-asynchronous-code">
<span id="s-async-tests"></span><span id="testing-asynchronous-code"></span><span id="async-tests"></span><h2>测试异步代码<a class="headerlink" href="#testing-asynchronous-code" title="永久链接至标题">¶</a></h2>
<div class="versionadded">
<span class="title">New in Django 3.1.</span> </div>
<p>如果你只是想测试异步视图的输出，标准测试客户端将在自己的异步循环中运行它们，而不需要你做任何额外的工作。</p>
<p>但是，如果你想为 Django 项目编写完全异步的测试，你需要考虑到几个问题。</p>
<p>首先，你的测试必须是测试类上的 <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> 方法（为了给它们一个异步的上下文）。Django 会自动检测到任何 <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> 的测试，并将它们封装在自己的事件循环中运行。</p>
<p>如果你从一个异步函数进行测试，你也必须使用异步测试客户端。这在任何测试中都可以作为 <code class="docutils literal notranslate"><span class="pre">django.test.AsyncClient</span></code> 或 <code class="docutils literal notranslate"><span class="pre">self.async_client</span></code> 使用。</p>
<p><code class="docutils literal notranslate"><span class="pre">AsyncClient</span></code> 具有与同步（普通）测试客户端相同的方法和签名，但有两个例外：</p>
<ul>
<li><p class="first">不支持 <code class="docutils literal notranslate"><span class="pre">follow</span></code> 参数。</p>
</li>
<li><p class="first">作为 <code class="docutils literal notranslate"><span class="pre">extra</span></code> 关键字参数传递的头信息不应该有同步客户端所要求的 <code class="docutils literal notranslate"><span class="pre">HTTP_</span></code> 前缀（参见 <a class="reference internal" href="#django.test.Client.get" title="django.test.Client.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Client.get()</span></code></a>）。例如，下面是如何设置 HTTP <code class="docutils literal notranslate"><span class="pre">Accept</span></code> 头：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">AsyncClient</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span>
<span class="gp">... </span>    <span class="s1">&#39;/customers/details/&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;fred&#39;</span><span class="p">,</span> <span class="s1">&#39;age&#39;</span><span class="p">:</span> <span class="mi">7</span><span class="p">},</span>
<span class="gp">... </span>    <span class="n">ACCEPT</span><span class="o">=</span><span class="s1">&#39;application/json&#39;</span>
<span class="gp">... </span><span class="p">)</span>
</pre></div>
</div>
</li>
</ul>
<p>使用 <code class="docutils literal notranslate"><span class="pre">AsyncClient</span></code> 任何提出请求的方法都必须被等待：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">test_my_thing</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="n">response</span> <span class="o">=</span> <span class="k">await</span> <span class="bp">self</span><span class="o">.</span><span class="n">async_client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;/some-url/&#39;</span><span class="p">)</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>
</pre></div>
</div>
<p>异步客户端也可以调用同步视图；它通过 Django 的 <a class="reference internal" href="../async.html"><span class="doc">异步请求路径</span></a> 运行，它支持这两种方式。任何通过 <code class="docutils literal notranslate"><span class="pre">AsyncClient</span></code> 调用的视图都会得到一个 <code class="docutils literal notranslate"><span class="pre">ASGIRequest</span></code> 对象作为它的 <code class="docutils literal notranslate"><span class="pre">request</span></code>，而不是普通客户端创建的 <code class="docutils literal notranslate"><span class="pre">WSGIRequest</span></code>。</p>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p>如果你使用的是测试装饰器，它们必须是异步兼容的，以确保它们正确工作。Django 内置的装饰器会正常工作，但第三方的装饰器可能会出现无法执行的情况（它们会“包装”执行流程中错误的部分，而不是你的测试）。</p>
<p>如果你需要使用这些装饰器，那么你应该用 <a class="reference internal" href="../async.html#asgiref.sync.async_to_sync" title="asgiref.sync.async_to_sync"><code class="xref py py-func docutils literal notranslate"><span class="pre">async_to_sync()</span></code></a> 来装饰你的测试方法:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">asgiref.sync</span> <span class="kn">import</span> <span class="n">async_to_sync</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span>

<span class="k">class</span> <span class="nc">MyTests</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="nd">@mock</span><span class="o">.</span><span class="n">patch</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
    <span class="nd">@async_to_sync</span>
    <span class="k">async</span> <span class="k">def</span> <span class="nf">test_my_thing</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-email-services">
<span id="s-topics-testing-email"></span><span id="email-services"></span><span id="topics-testing-email"></span><h2>邮件服务<a class="headerlink" href="#email-services" title="永久链接至标题">¶</a></h2>
<p>如果你的任何 Django 视图使用 <a class="reference internal" href="../email.html"><span class="doc">Django 的邮件功能</span></a> 发送电子邮件，你可能不想每次使用该视图运行测试时都发送电子邮件。出于这个原因，Django 的测试运行器会自动将所有 Django 发送的邮件重定向到一个虚拟的发件箱。这让你可以测试发送邮件的每一个方面——从发送邮件的数量到每封邮件的内容——而不用实际发送邮件。</p>
<p>测试运行器通过透明的将正常的邮件后端替换为测试后端来实现。（别担心——这对 Django 之外的其他邮件发送器没有影响，比如你机器的邮件服务器，如果你正在运行一个的话。）</p>
<dl class="data">
<dt id="django.core.mail.django.core.mail.outbox">
<code class="descclassname">django.core.mail.</code><code class="descname">outbox</code><a class="headerlink" href="#django.core.mail.django.core.mail.outbox" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>在测试运行过程中，每一封发出的邮件都会保存在 <code class="docutils literal notranslate"><span class="pre">django.core.mail.outbox</span></code> 中。这是所有已经发送的 <a class="reference internal" href="../email.html#django.core.mail.EmailMessage" title="django.core.mail.EmailMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">EmailMessage</span></code></a> 实例的列表。 <code class="docutils literal notranslate"><span class="pre">outbox</span></code> 属性是一个特殊的属性，只有在使用 <code class="docutils literal notranslate"><span class="pre">locmem</span></code> 邮件后端时才会创建。它通常不作为 <a class="reference internal" href="../email.html#module-django.core.mail" title="django.core.mail: Helpers to easily send email."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.core.mail</span></code></a> 模块的一部分存在，你也不能直接导入它。下面的代码展示了如何正确访问这个属性。</p>
<p>下面是一个检查 <code class="docutils literal notranslate"><span class="pre">django.core.mail.outbox</span></code> 长度和内容的测试示例：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> <span class="n">mail</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span>

<span class="k">class</span> <span class="nc">EmailTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_send_email</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Send message.</span>
        <span class="n">mail</span><span class="o">.</span><span class="n">send_mail</span><span class="p">(</span>
            <span class="s1">&#39;Subject here&#39;</span><span class="p">,</span> <span class="s1">&#39;Here is the message.&#39;</span><span class="p">,</span>
            <span class="s1">&#39;from@example.com&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;to@example.com&#39;</span><span class="p">],</span>
            <span class="n">fail_silently</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
        <span class="p">)</span>

        <span class="c1"># Test that one message has been sent.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">mail</span><span class="o">.</span><span class="n">outbox</span><span class="p">),</span> <span class="mi">1</span><span class="p">)</span>

        <span class="c1"># Verify that the subject of the first message is correct.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">mail</span><span class="o">.</span><span class="n">outbox</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">subject</span><span class="p">,</span> <span class="s1">&#39;Subject here&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>正如 <a class="reference internal" href="#emptying-test-outbox"><span class="std std-ref">之前</span></a>，在 Django <code class="docutils literal notranslate"><span class="pre">*TestCase</span></code> 中的每个测试开始时，测试发件箱都会被清空。要手动清空发件箱，将空列表分配给 <code class="docutils literal notranslate"><span class="pre">mail.outbox</span></code>：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> <span class="n">mail</span>

<span class="c1"># Empty the test outbox</span>
<span class="n">mail</span><span class="o">.</span><span class="n">outbox</span> <span class="o">=</span> <span class="p">[]</span>
</pre></div>
</div>
</div>
<div class="section" id="s-management-commands">
<span id="s-topics-testing-management-commands"></span><span id="management-commands"></span><span id="topics-testing-management-commands"></span><h2>管理命令<a class="headerlink" href="#management-commands" title="永久链接至标题">¶</a></h2>
<p>管理命令可以用 <a class="reference internal" href="../../ref/django-admin.html#django.core.management.call_command" title="django.core.management.call_command"><code class="xref py py-func docutils literal notranslate"><span class="pre">call_command()</span></code></a> 函数来测试。输出可以重定向到 <code class="docutils literal notranslate"><span class="pre">StringIO</span></code> 实例中：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">io</span> <span class="kn">import</span> <span class="n">StringIO</span>
<span class="kn">from</span> <span class="nn">django.core.management</span> <span class="kn">import</span> <span class="n">call_command</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span>

<span class="k">class</span> <span class="nc">ClosepollTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_command_output</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">out</span> <span class="o">=</span> <span class="n">StringIO</span><span class="p">()</span>
        <span class="n">call_command</span><span class="p">(</span><span class="s1">&#39;closepoll&#39;</span><span class="p">,</span> <span class="n">stdout</span><span class="o">=</span><span class="n">out</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertIn</span><span class="p">(</span><span class="s1">&#39;Expected output&#39;</span><span class="p">,</span> <span class="n">out</span><span class="o">.</span><span class="n">getvalue</span><span class="p">())</span>
</pre></div>
</div>
</div>
<div class="section" id="s-skipping-tests">
<span id="s-id3"></span><span id="skipping-tests"></span><span id="id3"></span><h2>忽略测试<a class="headerlink" href="#skipping-tests" title="永久链接至标题">¶</a></h2>
<p>unittest 库提供了 <a class="reference external" href="https://docs.python.org/3/library/unittest.html#unittest.skipIf" title="(在 Python v3.10)"><code class="xref py py-func docutils literal notranslate"><span class="pre">&#64;skipIf</span></code></a> 和 <a class="reference external" href="https://docs.python.org/3/library/unittest.html#unittest.skipUnless" title="(在 Python v3.10)"><code class="xref py py-func docutils literal notranslate"><span class="pre">&#64;skipUnless</span></code></a> 装饰器，允许你跳过测试，如果你事先知道这些测试在某些条件下会失败。</p>
<p>例如，如果你的测试需要一个特定的可选库才能成功，你可以用 <a class="reference external" href="https://docs.python.org/3/library/unittest.html#unittest.skipIf" title="(在 Python v3.10)"><code class="xref py py-func docutils literal notranslate"><span class="pre">&#64;skipIf</span></code></a> 来装饰测试用例。然后，测试运行器将报告测试没有被执行以及原因，而不是测试失败或完全省略测试。</p>
<p>为了补充这些测试跳过行为，Django 提供了两个额外的跳过装饰器。这些装饰器不是测试一个通用的布尔值，而是检查数据库的能力，如果数据库不支持一个特定的命名特性，则跳过测试。</p>
<p>装饰器使用一个字符串标识符来描述数据库特征。这个字符串对应于数据库连接特征类的属性。参见 <a class="reference external" href="https://github.com/django/django/blob/main/django/db/backends/base/features.py">django.db.backends.base.features.BaseDatabaseFeatures 类</a> 以获得可作为跳过测试基础的数据库特征的完整列表。</p>
<dl class="function">
<dt id="django.test.skipIfDBFeature">
<code class="descname">skipIfDBFeature</code>(<em>*feature_name_strings</em>)<a class="headerlink" href="#django.test.skipIfDBFeature" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>如果支持某个命名的数据库功能，则跳过装饰测试或 <code class="docutils literal notranslate"><span class="pre">TestCase</span></code>。</p>
<p>例如，如果数据库支持事务，下面的测试将不会被执行（例如，在PostgreSQL 下，它将 <em>不</em> 会运行，但在 MySQL 的 MyISAM 表下却可以）：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyTests</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="nd">@skipIfDBFeature</span><span class="p">(</span><span class="s1">&#39;supports_transactions&#39;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test_transaction_behavior</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># ... conditional test code</span>
        <span class="k">pass</span>
</pre></div>
</div>
<dl class="function">
<dt id="django.test.skipUnlessDBFeature">
<code class="descname">skipUnlessDBFeature</code>(<em>*feature_name_strings</em>)<a class="headerlink" href="#django.test.skipUnlessDBFeature" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>如果 <em>不</em> 支持某个命名的数据库功能，则跳过装饰测试或 <code class="docutils literal notranslate"><span class="pre">TestCase</span></code>。</p>
<p>例如，接下来的测试仅在支持事务的数据库下执行(如：可以是PostgreSQL，但不可以是使用MyISAM数据库引擎的MySQL):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyTests</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="nd">@skipUnlessDBFeature</span><span class="p">(</span><span class="s1">&#39;supports_transactions&#39;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test_transaction_behavior</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># ... conditional test code</span>
        <span class="k">pass</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">测试工具</a><ul>
<li><a class="reference internal" href="#the-test-client">测试客户端</a><ul>
<li><a class="reference internal" href="#overview-and-a-quick-example">概述和一个简单的例子</a></li>
<li><a class="reference internal" href="#making-requests">发出请求</a></li>
<li><a class="reference internal" href="#testing-responses">测试响应</a></li>
<li><a class="reference internal" href="#exceptions">例外</a></li>
<li><a class="reference internal" href="#persistent-state">持久状态</a></li>
<li><a class="reference internal" href="#setting-the-language">设置语言</a></li>
<li><a class="reference internal" href="#example">例如</a></li>
</ul>
</li>
<li><a class="reference internal" href="#provided-test-case-classes">提供的测试用例类</a><ul>
<li><a class="reference internal" href="#simpletestcase"><code class="docutils literal notranslate"><span class="pre">SimpleTestCase</span></code></a></li>
<li><a class="reference internal" href="#transactiontestcase"><code class="docutils literal notranslate"><span class="pre">TransactionTestCase</span></code></a></li>
<li><a class="reference internal" href="#testcase"><code class="docutils literal notranslate"><span class="pre">TestCase</span></code></a></li>
<li><a class="reference internal" href="#liveservertestcase"><code class="docutils literal notranslate"><span class="pre">LiveServerTestCase</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#test-cases-features">测试用例特性</a><ul>
<li><a class="reference internal" href="#default-test-client">默认测试客户端</a></li>
<li><a class="reference internal" href="#customizing-the-test-client">自定义测试客户端</a></li>
<li><a class="reference internal" href="#fixture-loading">辅助工具加载</a></li>
<li><a class="reference internal" href="#urlconf-configuration">URLconf 配置</a></li>
<li><a class="reference internal" href="#multi-database-support">多数据库支持</a></li>
<li><a class="reference internal" href="#overriding-settings">覆盖配置</a></li>
<li><a class="reference internal" href="#emptying-the-test-outbox">清空测试发件箱</a></li>
<li><a class="reference internal" href="#assertions">断言</a></li>
<li><a class="reference internal" href="#tagging-tests">标记测试</a></li>
</ul>
</li>
<li><a class="reference internal" href="#testing-asynchronous-code">测试异步代码</a></li>
<li><a class="reference internal" href="#email-services">邮件服务</a></li>
<li><a class="reference internal" href="#management-commands">管理命令</a></li>
<li><a class="reference internal" href="#skipping-tests">忽略测试</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="overview.html"
                        title="上一章">编写并运行测试</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="advanced.html"
                        title="下一章">进阶测试主题</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/topics/testing/tools.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="overview.html" title="编写并运行测试">previous</a>
     |
    <a href="../index.html" title="使用 Django" accesskey="U">up</a>
   |
    <a href="advanced.html" title="进阶测试主题">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>